算法分析与设计第十六周

来源:互联网 发布:铝合金和塑钢知乎 编辑:程序博客网 时间:2024/06/06 20:18

这里写图片描述

分析:每次移除一个数,要尽可能使前面的数最小,因为前面的数的权值最大。而删除一个数,会导致后面紧接着的一个数代替删除的数的位置。所以在一次移除操作中,从前往后检查,一旦发现某个数后继的数更小,则删除此数。复杂度为o(k*n),可以采用递归的方法实现。(然而递归代码LeetCode显示内存超出,应该是栈溢出了,本地测试没问题。下面先给出递归代码,后面再给出迭代方法)

递归代码

class Solution {public:    string removeKdigits(string num, int k) {        if (k == 0)            return num == "" ? "0" : num;        if (num.length() == k)            return "0";        if (num == "")            return "0";        string next = "";        for (int i = 0; i < num.length() - 1;)        {            if (num[i + 1] >= num[i])            {                next += num[i];                ++i;            }            else            {                ++i;                while (i < num.length())                {                    next += num[i];                    ++i;                }               // break;            }        }        int i ;        //消除前导0        for (i = 0; i < next.length() && next[i] == '0'; ++i);        next = next.substr(i);        return removeKdigits(next, k - 1);    }};

迭代代码:

class Solution {public:    string removeKdigits(string num, int k) {        if (num.length() == k || num == "")            return "0";        if (k == 0)            return num;        int len = num.length();        while (k-- > 0)        {             string next = "";        for (int i = 0; i < len - 1;)        {            if (num[i + 1] >= num[i])            {                next += num[i];                ++i;            }            else            {                ++i;                while (i < num.length())                {                    next += num[i];                    ++i;                }               // break;            }        }        int j ;        for (j = 0; j < next.length() && next[j] == '0'; ++j);        next = next.substr(j);        len = next.length();        num = next;        }        return num == "" ? "0" : num;    }};

通过截图
这里写图片描述

原创粉丝点击