首页 > 代码库 > 316. Remove Duplicate Letters
316. Remove Duplicate Letters
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"
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
根据字符串大小排序:优先把最小的字符放在前面,这样生成的字符肯定最小。问题是如何找出可以放在第一的最小字符呢?
首先,找出s中出现的所有字符最后一次出现的位置,再从中找到最小的位置index1,从0到index1中找到最小字符,把选出来的字符做好标记
我们可以选从0到index中的任意一个字符。其他所有待选字符都还在index-end中,等待之后选。
然后在剩余待选字符中找到最后一次出现位置的最小值index2,再从index1+1 到index2里找出最小字符,把选出来的字符做好标记
重复…
时间复杂度O(n)
public class Solution { public String removeDuplicateLetters(String s) { int[] index = new int[26]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { index[s.charAt(i) - ‘a‘] = i + 1; } int start = 0; int cur = findMinIndex(index); // Return the index of the characters‘ last occurance in the string while (cur >= 0) { int chosen = findMinChar(s, start, cur, index); // Find the index of the smallest char from 0 to ‘cur‘ in the string start = chosen + 1; index[s.charAt(chosen) - ‘a‘] = 0; sb.append(s.charAt(chosen)); cur = findMinIndex(index); } return sb.toString(); } private int findMinIndex(int[] index) { int min = Integer.MAX_VALUE; for (int i = 0; i < 26; i++) { if (index[i] > 0 && min > index[i]) { min = index[i]; } } if (min == Integer.MAX_VALUE) { return -1; } else { return min - 1; } } private int findMinChar(String s, int start, int end, int[] index) { int min = -1; char c = ‘{‘; for (int i = start; i <= end; i++) { if (index[s.charAt(i) - ‘a‘] > 0 && c > s.charAt(i)) { c = s.charAt(i); min = i; } } return min; } }
316. Remove Duplicate Letters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。