标签:letter find contains log ring his lex ever test
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.
时间复杂度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; } }
标签:letter find contains log ring his lex ever test
原文地址:http://www.cnblogs.com/yuchenkit/p/7169500.html