首页 技术 正文
技术 2022年11月17日
0 收藏 877 点赞 4,141 浏览 925 个字

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 "bcabc"
Return "abc"

Given "cbacdcbc"
Return "acdb"

思路:采用贪心算法,对于给定的字符串S,找到所有结果的最小前缀(即最小的字母),假如有多个最小前缀,则选择最左侧的。

令最终选择的最小前缀的下标为pos,则删掉s[pos]左侧的所有字符,并删掉剩下字符串中所有与s[pos]相等的字符。

C++中将某个特定字符从所有出现的位置删掉可以这样实现:

s.erase(remove(s.begin(), s.end(), theCharacterNeedtoRemove), s.end());

其中remove函数需要使用algorithm库文件。算法复杂度为O(26 * n) = O(n)

 class Solution {
public:
string removeDuplicateLetters(string s) {
vector<int> alp(, -);
for (int i = , n = s.size(); i < n; i++)
alp[(int)(s[i] - 'a')] = i;
int pos = -;
for (int i = , n = s.size(); i < n; i++)
{
int ind = (int)(s[i] - 'a');
if (alp[ind] == -) continue;
if (pos == - || s[pos] > s[i]) pos = i;
if (alp[ind] == i) break;
}
if (s == "" || pos == -) return "";
char cand = s[pos];
s = s.substr(pos + );
s.erase(remove(s.begin(), s.end(), cand), s.end());
return cand + removeDuplicateLetters(s);
}
};
上一篇: JSON 中的 key
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905