93. Restore IP Addresses

本文介绍了一种使用C++解决字符串中仅包含数字的IP地址还原问题的方法。通过递归函数helper实现,返回所有可能的有效IP地址组合。示例输入为25525511135,输出包括[255.255.11.135255.255.111.35]。代码运行时间为4ms,优于23.68%的在线提交。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

 

AC code:

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        helper(0, s, res, "", 0);
        return res;
    }
    
    void helper(int count, string s, vector<string>& res, string ret, int index) {
        if (count > 4) return;
        if (count == 4 && index == s.length())
            res.push_back(ret);
        for (int i = 1; i < 4; i++) {
            if (index+i > s.length()) break;
            string temp = s.substr(index, i);
            if(temp[0] == '0' && temp.length() > 1 || atoi(temp.c_str()) > 255) continue;
            string next = ret + temp;
            helper(count+1, s, res, next+(count == 3 ? "" : "."), index+i);
        }
    }
};

Runtime: 4 ms, faster than 23.68% of C++ online submissions for Restore IP Addresses.

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/9867423.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值