Categories
木有技术

LeetCode 402. Remove K Digits

https://leetcode.com/problems/remove-k-digits/description/
如果直接用DFS做的话轻轻松松就会stack overflow。
这道题可以用贪心法,题目换个思路说就是尽可能保证得到的数字是递增的。在拿到一个新数字时,尽可能(只要还能删)把该数字之前的比它大的数字移掉。
贪心法之所以能用是因为我们去尽量保证了a1<a2< …< x< y,如果这些个数字里要选一个删掉的话,肯定是删掉y带来的结果最好。

class Solution {
public:
	string removeKdigits(string num, int k) {
		const int digits = num.size() - k;
        char* stack = new char[num.size()]; // mem leak but I DONT CARE!
        int top = 0;
        for (int i = 0; i < num.size(); ++i)
        {
            char c = num[i];
            while (top > 0 && stack[top-1] > c && k > 0)
            {
                top--;
                k--;
            }
            stack[top++] = c;
        }
        int idx = 0;
        while (idx < digits && stack[idx] == '0')
            idx++;
        return idx == digits ? "0" : string(stack + idx, digits - idx);
	}
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.