[leetcode]316. Remove Duplicate Letters
来源:互联网 发布:数据库监控自动化方案 编辑:程序博客网 时间:2024/06/08 02:45
题目链接:https://leetcode.com/problems/remove-duplicate-letters/description/
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, firstly check if the res from back to begin is larger than s[i] and will occur after the current position i. If meet both condition, 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 res.empty() or 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 lastIdx[26]={0},included[26]={0}; string res; //generate lastIdx array for(int i=0;i<s.size();i++) lastIdx[s[i]-'a']=i; //scan s from left to right for(int i=0;i<s.size();i++) { // if s[i] is not included if(!included[s[i]-'a']) { // pop res as much as possible to reduce res while(!res.empty() && s[i]<res.back() && lastIdx[res.back()-'a']>i) { 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; }};
- Leetcode 316. Remove Duplicate Letters
- Leetcode 316. Remove Duplicate Letters
- leetcode 316. Remove Duplicate Letters
- 316. Remove Duplicate Letters LeetCode
- LeetCode 316. Remove Duplicate Letters
- leetcode.316. Remove Duplicate Letters
- LeetCode 316. Remove Duplicate Letters
- [leetcode]316. Remove Duplicate Letters
- leetcode 316. Remove Duplicate Letters
- leetcode 316. Remove Duplicate Letters
- leetcode 316. Remove Duplicate Letters
- leetcode Remove Duplicate Letters
- leetcode: Remove Duplicate Letters
- LeetCode Remove Duplicate Letters
- 《leetCode》:Remove Duplicate Letters
- Leetcode: Remove Duplicate Letters
- leetcode--Remove Duplicate Letters
- [Leetcode]Remove Duplicate Letters
- 使用贝塞尔曲线和Pathmeasure画粘连体
- Ubuntu14.04 流媒体服务器
- Junit的使用
- 九度 OJ 1153:括号匹配问题
- 工厂模式
- [leetcode]316. Remove Duplicate Letters
- 创建Windows服务(C++)
- 数据结构之元组
- detailview
- 前端input与后台交互
- Linux环境下Python的安装过程
- js删除数组元素、清空数组的简单方法(必看)
- Android 6.0: 动态权限管理的解决方案
- 等价类划分法设计测试用例