【LeetCode】93. 复原IP地址 (C++)

原题地址:https://leetcode-cn.com/problems/restore-ip-addresses/submissions/

题目描述:

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

示例:

输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]

解题方案:

这道题在刚开始解的时候忘记在一层遍历完之后要去掉点,意识到之后又思考了很久如何去掉点。没有意识到的问题还有最后剩下的数字可能不足3个,以及类似“00”,“010”这种情况不合理。在网上看到说到最后一层时直接计算剩余所有数字,这种想法比我做的要简单得多了,不过实验了一下发现时间复杂度没有改善。这道题总体来说做的质量比较低,想得过于复杂,没有想到比较直接的方法。这也是我经常会遇到的一个问题...

代码:

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        string temp;
        vector<string> result;
        getAns(temp, s, 0, result, 0);
        return result;
    }
    void getAns(string temp, string s, int pos, vector<string>& result, int time)
    {            
        if(pos >= s.length() && time == 4)
        {
            result.push_back(temp);
        }
        else
        {
            int m = s.length() - pos;
            m = m > 3 ? 3 : m;
            for(int i = 1; i <= m; i ++)
            {
                if(time >= 4)
                {
                    return;
                }    
                string s1 = s.substr(pos, i);
                if(s1[0] == '0' && s1.length() > 1)
                    continue;
                stringstream ss;
                int num;
                ss << s1;
                ss >> num;
                if(num < 0 || num > 255)
                    continue;
                temp.append(s1);
                if(time < 3)
                    temp.append(".");
                time ++;
                pos += i;
                getAns(temp, s, pos, result, time);
                pos -= i;
                time --;
                
                if(time < 3)
                    temp = temp.substr(0, temp.length() - i - 1);
                else
                    temp = temp.substr(0, temp.length() - i);
            }
            
        }
    }
};

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值