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”

 核心思路其实是一个贪心的思路,需要观察到,对于目前需要加进来的点,如果他前面的字母比他大且还有余量,那么就应该在后面出现,所以将前面的数据删除!!!

class Solution {
    public String removeDuplicateLetters(String s) {
        
        Deque stack = new ArrayDeque<>();
        char[] c = s.toCharArray();
        int[] count = new int[26];
        boolean[] visited = new boolean[26];
        
        for(char ch : c){
            count[ch - 'a']++;
        }
        
        for(char ch : c){
            count[ch - 'a']--;
            if(visited[ch - 'a'])continue;
            
            while(!stack.isEmpty() && stack.peek() > ch && count[stack.peek() - 'a'] > 0){
                visited[stack.pop() - 'a'] = false;
            }
            stack.push(ch);
            visited[ch - 'a'] = true;
        }
        
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty())
            sb.append(stack.pop());
        
        return sb.reverse().toString();
        
        
    }
}

你可能感兴趣的:(数据结构与算法)