316. Remove Duplicate Letters
2016-05-19 21:40
411 查看
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example:
Given
Return
Given
Return
Credits:
Special thanks to
@dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
题目的意思是删除重复的元素,同时若有重复的,尽量把小的排在前面。
采用两个hash表记录,一个记录个数,另一个记录是否被访问。遍历源string,记录hash表中对应char项减一,若被访问了说明,已经在结果中处于正确位置,若没有被访问过,则检查结果string的最后一个char是不是大于当前char,且个数记录表中不为0(说明,还存在这样的char在当前char的后面),则循环检查结果string的最后一个单词,直到满足规定。结果string 初始化时候为“0”。
代码如下:
class Solution {
public:
string removeDuplicateLetters(string s) {
string res="0";
int m1[256]={0};
int visited[256]={0};
for(auto p:s) m1[p]++;
for(auto p:s)
{
--m1[p];
if(visited[p]) continue;
while(m1[res.back()]&&p<res.back())
{
visited[res.back()]=0;
res.pop_back();
}
visited[p]=1;
res+=p;
}
return res.substr(1);
}
};
Example:
Given
"bcabc"
Return
"abc"
Given
"cbacdcbc"
Return
"acdb"
Credits:
Special thanks to
@dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
题目的意思是删除重复的元素,同时若有重复的,尽量把小的排在前面。
采用两个hash表记录,一个记录个数,另一个记录是否被访问。遍历源string,记录hash表中对应char项减一,若被访问了说明,已经在结果中处于正确位置,若没有被访问过,则检查结果string的最后一个char是不是大于当前char,且个数记录表中不为0(说明,还存在这样的char在当前char的后面),则循环检查结果string的最后一个单词,直到满足规定。结果string 初始化时候为“0”。
代码如下:
class Solution {
public:
string removeDuplicateLetters(string s) {
string res="0";
int m1[256]={0};
int visited[256]={0};
for(auto p:s) m1[p]++;
for(auto p:s)
{
--m1[p];
if(visited[p]) continue;
while(m1[res.back()]&&p<res.back())
{
visited[res.back()]=0;
res.pop_back();
}
visited[p]=1;
res+=p;
}
return res.substr(1);
}
};
相关文章推荐
- Java数组
- 蓝桥杯练习系统—算法训练 P1102
- 使用Cookie进行会话管理
- 第十三周
- Linux及安全——模块
- MongoDB 数组修改更新方法,很不错拿出来分享一下
- Box2D C++ 教程-环境设置
- 第5章:概率分析与随机算法
- 树状数组
- Mybatis中运用小技巧(一)
- Elsevier LaTeX instructions 排版指导
- 输出乘法口诀表
- winform学习-----理解小概念-20160518
- JS闭包之深刻理解
- MySQL入门--查看当前的mysql客户端版本号、当前系统时间、登陆的用户
- 开发还是算法,一直困惑我的问题
- 字符串初始化的方式
- 线上遇到插入重复数据(重复提交)
- SCI期刊分区七问
- 异或和同或