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

Given "bcabc"
Return "abc"

Given "cbacdcbc"
Return "acdb"


Solution: reference

After determining the greedy choice s[i], we get a new string s' from s by

  1. removing all letters to the left of s[i],
  2. removing all s[i]'s from s.

public String removeDuplicateLetters(String s) {
        int[] count = new int[26];
        int pos = 0;
        for(int i=0; i<s.length(); i++) count[s.charAt(i) - 'a']++;
        for(int i=0; i<s.length(); i++) {
            if(s.charAt(i)< s.charAt(pos)) pos = i;
            if(--count[s.charAt(i) - 'a'] == 0) break;
        }
        return s.length() == 0? "" : s.charAt(pos) + removeDuplicateLetters(s.substring(pos+1).replaceAll(""+ s.charAt(pos), ""));
    }




你可能感兴趣的:(LeetCode,gready)