316. Remove Duplicate Letters and 402. Remove K Digits

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值