316 Remove Duplicate

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.

Given "bcabc"
Return "abc"

Given "cbacdcbc"
Return "acdb"
每个字母只留一个,而且保证字典序最小。
从前往后扫描,还要往前看一个检出是否删除的,要用stack解。stack里记录的就是待用的字母。
首先要有一个counter记录下每个字母的总个数,stack删除字母的时候如果后面还有余量,则可以放心删除。
还有个关键词: once and only once。需要一个数据结构记录是否使用这个字母,可以用boolean。
public class Solution {
    public String removeDuplicateLetters(String s) {
        ArrayDeque<Character> stk = new ArrayDeque<Character>();
        int[] counter = new int[26];
        boolean[] visited = new boolean[26];
        char[] chs = s.toCharArray();
        
        for(char c: chs){
            counter[c - 'a']++;
        }
        
        
        for(char c : chs){
            counter[c - 'a']--;
            if(visited[c - 'a']) continue;
            
            while(!stk.isEmpty() && stk.peekLast() > c && counter[stk.peekLast() -'a'] > 0){
                visited[stk.peekLast() - 'a'] = false;
                stk.pollLast();
            }
            stk.addLast(c);
            visited[c-'a'] = true;
        }
        
        StringBuilder sb = new StringBuilder();
        for(char c: stk){
            sb.append(c);
        }
        
        return sb.toString();
    }
}

402 Remove K Digits

Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible
Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

stk结构也可以用数组加顶点指针模拟。用法如下。

public class Solution {
    public String removeKdigits(String num, int k) {
        int digit = num.length() - k;
        char[] stk = new char[num.length()];
        int top = 0;
        for(char c: num.toCharArray()){
            while(top > 0 && stk[top-1] > c && k > 0){
                k--;
                top--;
            }
            stk[top++] = c;
        }
        
        int idx = 0;
        while(idx < digit && stk[idx] == '0') idx++;
        
        return idx == digit ? "0" : new String(stk, idx, digit-idx);
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。