LeetCode——Restore IP Addresses

本文介绍了一个算法问题:如何将仅包含数字的字符串恢复为所有可能的有效IP地址组合。通过递归搜索的方法,文章详细展示了如何从给定字符串中找出所有合法的IP地址,并提供了具体的实现代码。

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

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

» Solve this problem


class Solution {
private:
    void search(vector<string> &ans, string &s, int num, int idx, string t) {
        string tmp = "";
        if (num == 3 && idx + 1 <= s.size() - 1) {
            if (s[idx + 1] == '0' && idx + 1 < s.size() - 1) {
                return;
            }
            tmp = s.substr(idx + 1, s.size() - idx - 1);            
            if (atoi(tmp.c_str()) <= 255) {
                ans.push_back(t + tmp);                
            }
        }   
        else {        
            for (int i = idx + 1; i < s.size(); i++) {
                tmp += s[i];            
                if (atoi(tmp.c_str()) <= 255) {
                    search(ans, s, num + 1, i, t + tmp + '.');
                }
                if (tmp[0] == '0') {
                    break;
                }
            }
        }
    }
    
public:
    vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> ans;
        search(ans, s, 0, -1, "");
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值