【leetcode】316. Remove Duplicate Letters

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 1:

Input: "bcabc"
Output: "abc"

Example 2:

Input: "cbacdcbc"
Output: "acdb"

題解如下:

class Solution {
    public String removeDuplicateLetters(String s) {
        if(s == null || s.length() <= 0) {
            return "";
        }
        char[] arr = s.toCharArray();
        int[] cnt = new int[26];//用於記錄每個字母出現的次數
        for(char c:arr) {
            cnt[c-'a']++;
        }
        int pos = 0;
        for(int i = 0;i < arr.length;i++) {
            if(arr[i] < arr[pos])
                pos = i;
            if(--cnt[arr[i]-'a'] == 0) {
                break;
            }
        }
        
        return arr[pos] + removeDuplicateLetters(s.substring(pos+1).replaceAll(arr[pos]+"",""));
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章