[LeetCode] Restore IP Addresses 解题报告

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

[解题思路]
递归的将数字串分成四个部分,每个部分满足0<=p<=255。要注意一些边界case,比如010是没有意思的,“0.10. 010.1”。

1:       vector<string> restoreIpAddresses(string s) {   
2: vector<string> col;
3: string ip;
4: partitionIP(s, 0, 0, ip, col);
5: return col;
6: }
7: void partitionIP(string s, int startIndex, int partNum,
8: string resultIp, vector<string>& col)
9: {
10: //max: 3 bits per partition
11: if(s.size() - startIndex > (4-partNum)*3) return;
12: //min: 1 bit per partition
13: if(s.size() - startIndex < (4-partNum)) return;
14: if(startIndex == s.size() && partNum ==4)
15: {
16: resultIp.resize(resultIp.size()-1);
17: col.push_back(resultIp);
18: return;
19: }
20: int num =0;
21: for(int i = startIndex; i< startIndex +3; i++)
22: {
23: num = num*10 + (s[i]-'0');
24: if(num<=255)
25: {
26: resultIp+=s[i];
27: partitionIP(s, i+1, partNum+1, resultIp+'.', col);
28: }
29: if(num ==0)//0.0.0.0 valid, but need to avoid 0.1.010.01
30: {
31: break;
32: }
33: }
34: }



转载于:https://www.cnblogs.com/codingtmd/archive/2013/01/01/5078966.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值