**316. Remove Duplicate Letters
作者:互联网
class Solution { public String removeDuplicateLetters(String s) { int[] lastIndex = new int[26]; for (int i = 0; i < s.length(); i++){ lastIndex[s.charAt(i) - 'a'] = i; // track the lastIndex of character presence } boolean[] seen = new boolean[26]; // keep track seen Stack<Integer> st = new Stack(); for (int i = 0; i < s.length(); i++) { int curr = s.charAt(i) - 'a'; if (seen[curr]) continue; // if seen continue as we need to pick one char only while (!st.isEmpty() && st.peek() > curr && i < lastIndex[st.peek()]){ seen[st.pop()] = false; // pop out and mark unseen } st.push(curr); // add into stack seen[curr] = true; // mark seen } StringBuilder sb = new StringBuilder(); for(int i:st){ sb.append((char)(i+'a')); } return sb.toString(); } }
标签:Letters,int,316,st,Duplicate,lastIndex,new,seen,curr 来源: https://www.cnblogs.com/feiflytech/p/16169559.html