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.app
Example:
Given "bcabc"
Return "abc"uiGiven "cbacdcbc"
Return "acdb"code
复杂度
O(N), O(N)ci
思路
用一个stack,每次考虑当前的字符大小和stack的顶端字符的大小,若是当前字符比较小的话,则能够poll出stack顶端的字符,将当前的字符放进stack中。须要维持了一个array判断当前字符在剩余字符串中的出现次数,考虑可否将这个字符从栈中弹出。rem
代码字符串
public String removeDuplicateLetters(String s) { Stack<Character> stack = new Stack<>(); int[] arr = new int[26]; boolean[] visited = new boolean[26]; for(int i = 0; i < s.length(); i ++) { arr[s.charAt(i) - 'a'] ++; } // for(int i = 0; i < s.length(); i ++) { char ch = s.charAt(i); arr[ch - 'a'] --; if(visited[ch - 'a']) continue; if(!stack.isEmpty() && ch < stack.peek()) { // while(!stack.isEmpty() && arr[stack.peek() - 'a'] > 0 && ch < stack.peek()) { char temp = stack.pop(); visited[temp - 'a'] --; } } visited[ch - 'a'] = true; stack.push(ch); } // build the string; StringBuilder builder = new StringBuilder(); while(!stack.isEmpty()) { builder.append(stack.pop()); } return builder.reverse().toString(); }