1. 程式人生 > >316. Remove Duplicate Letters

316. Remove Duplicate Letters

tel result example test case pos 一次 https order tar

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.


根據字符串大小排序:優先把最小的字符放在前面,這樣生成的字符肯定最小。問題是如何找出可以放在第一的最小字符呢? 首先,找出s中出現的所有字符最後一次出現的位置,再從中找到最小的位置index1,從0到index1中找到最小字符,把選出來的字符做好標記 我們可以選從0到index中的任意一個字符。其他所有待選字符都還在index-end中,等待之後選。 然後在剩余待選字符中找到最後一次出現位置的最小值index2,再從index1+1 到index2裏找出最小字符,把選出來的字符做好標記 重復…

時間復雜度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;
    }
}

316. Remove Duplicate Letters