316. Remove Duplicate Letters

316. Remove Duplicate Letters

題目連接:https://leetcode.com/problems...python

用一個stack來作,stack裏面的字母按增序來排,出現top>cur的時候要把top給pop出來,注意一點是若是後面沒有top的話,就不能pop出來,因此先要用個hashmap來保存每一個字母出現的次數,次數到0說明後面沒有這個字母了,還須要一個visited數組來保存已經在stack裏面的字母web

  1. pop: while top > cur && map[top] > 0數組

  2. push: when !visited[cur]oop

loop invariant是(0, i)是到i爲止最小的字母order結果。code

public class Solution {
    public String removeDuplicateLetters(String s) {
        // count the number of each character
        int[] map = new int[26];
        for(char c : s.toCharArray()) {
            map[c - 'a']++;
        }
        // stack to store the smallest lexi order
        char[] stack = new char[s.length()];
        // visited to record already added letter
        boolean[] visited = new boolean[26];
        int i = 0;
        for(char c : s.toCharArray()) {
            map[c - 'a']--;
            if(visited[c - 'a']) continue;
            // pop top character if it is > c && there are remains in the right
            while(i > 0 && stack[i-1] > c && map[stack[i-1] - 'a'] > 0) {
                visited[stack[i-1] - 'a'] = false;
                i--;
            }
            stack[i++] = c;
            visited[c-'a'] = true;
        }
        
        return new String(stack, 0, i);
    }
}

以及枚舉的作法,由於這題只有26個字母,枚舉的複雜度是O(26*N),參考博客:
http://bookshadow.com/weblog/...blog

還有先把string排序,而後從小到大取字母的寫法,參考discussion:
https://discuss.leetcode.com/...排序

相關文章
相關標籤/搜索