LeetCode 316. Remove Duplicate Letters

原题链接在这里:https://leetcode.com/problems/remove-duplicate-letters/

题目:

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

Input: "bcabc"
Output: "abc"

Example 2:

Input: "cbacdcbc"
Output: "acdb"

题解:

Mark the last appearance of each char in s.

For current char, if it is not added in stack.

Keep checking the last added char, if it is bigger than current char and its last appearence is after current index i. Then it could be added later.

Pop it out and mark it unused.

Eventually the chars in stack are expected result.

Time Complexity: O(n).  = s.length().

Space: O(1).

AC Java:

 1 class Solution {
 2     public String removeDuplicateLetters(String s) {
 3         int [] last = new int[26];
 4         for(int i = 0; i<s.length(); i++){
 5             last[s.charAt(i)-'a'] = i;
 6         }
 7         
 8         Stack<Character> stk = new Stack<>();
 9         boolean [] used = new boolean[26];
10         for(int i = 0; i<s.length(); i++){
11             char c = s.charAt(i);
12             if(used[c-'a']){
13                 continue;
14             }
15             
16             
17             while(!stk.isEmpty() && stk.peek()>c && last[stk.peek()-'a']>i){
18                 char top = stk.pop();
19                 used[top-'a'] = false;
20             }
21             
22             stk.push(c);
23             used[c-'a'] = true;
24         }
25         
26         StringBuilder sb = new StringBuilder();
27         for(char c : stk){
28             sb.append(c);
29         }
30         
31         return sb.toString();
32     }
33 }

类似Smallest Subsequence of Distinct Characters.

posted @ 2016-03-04 12:33  Dylan_Java_NYC  阅读(327)  评论(0编辑  收藏  举报