Leetcode201: Remove Duplicate Letters
来源:互联网 发布:闲杂软件 编辑:程序博客网 时间:2024/04/29 17:57
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"
The key is to get an auxiliary array to save the index of the last occurence of each letter in S. Then we do greedy algorithm: scan the string from left to right, for the current letter s[i], if it is already included then move on, if not, check if the previously included letter in res (from back to begin) if larger than s[i], if yes and such res.back() letter has occurence after the current position i, then drop it from res and reset the included flag (since it can reduce res and res.back() can still be added back later on), and repeat to check the new res.back(). If s[i]> res.back() or res.back() has no occurence after i, then, just add s[i] to res. Two key arrays are used in the following code lastIdx[i]: the last occurence index of letter 'a'+i in s included[i]: if 'a'+i is already included in res
class Solution {public: string removeDuplicateLetters(string s) { int sLen = s.size(), i, lastIdx[26]={0},resLen=0, included[26]={0}; string res; for(i=sLen-1; i>=0 && resLen<26;--i) {//generate lastIdx array if(!lastIdx[s[i]-'a']) { lastIdx[s[i]-'a'] = i; ++resLen; } } for(i=0; i<sLen;++i) { //scan s from left to right if(!included[s[i]-'a']) { // if s[i] is not included in s[i] while(!res.empty() && s[i]<res.back() && lastIdx[res.back()-'a']>i) { // pop res as much as possible to reduce res included[res.back()-'a'] = 0; res.pop_back(); } included[s[i]-'a'] = 1; // add s[i] to res res.push_back(s[i]); } } return res; }};
- Leetcode201: Remove Duplicate Letters
- leetcode Remove Duplicate Letters
- Remove Duplicate Letters
- Remove Duplicate Letters
- Remove Duplicate Letters
- Remove Duplicate Letters leetCode316
- leetcode: Remove Duplicate Letters
- LeetCode Remove Duplicate Letters
- 《leetCode》:Remove Duplicate Letters
- Leetcode: Remove Duplicate Letters
- leetcode--Remove Duplicate Letters
- [Leetcode]Remove Duplicate Letters
- Remove Duplicate Letters
- Remove Duplicate Letters
- 316. Remove Duplicate Letters
- 316. Remove Duplicate Letters
- 316. Remove Duplicate Letters
- Remove Duplicate Letters
- ERROR: ORA-01033: ORACLE initialization or shutdown in progress
- iOS (Category)runtime动态添加属性
- fragment的简单使用,点击底下导航栏切换activity的fragment。
- 错误删除数据或清空数据怎样可以找回
- xcode7以上找不到.dylib,一招帮你解决
- Leetcode201: Remove Duplicate Letters
- java protected访问权限小结
- processing - MySQL example1-conntction(), query() , next() , getInt(1)
- UICollectionView 运用
- iOS状态栏隐藏
- OC-057.copy和MutableCopy的使用
- binbinyang---百度地图定位通过启动application. 一运行就能得到当前定位信息
- 在表维护生成器中添加F4及自动带出描述
- 分享Android双人五子棋对战