Leetcode Restore IP Address
来源:互联网 发布:广州新科佳都科技 知乎 编辑:程序博客网 时间:2024/05/20 00:12
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 the problem on leetcode
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
//传进去的s是一个大数
vector<string> res;
if (s.size()<4||s.size()>12) return res;
dfs(res,"",s,0);
return res;
}
void dfs(vector<string> &res,string tmp,string s,int pos)
{
//pos表示递归深度,4个层次,0,1,2,3
if(pos==3&&isvalid(s))
{ //第四层,只需要判断合法,就可以加入tmp
res.push_back(tmp+s);
return;
}
for(int i=1;i<4&&i<s.size();i++)
{
//subset函数定义
//1,2,3个字符
string sub_str=s.substr(0,i);
if(isvalid(sub_str))
{
dfs(res,tmp+sub_str+'.',s.substr(i),pos+1);
//substr(),i位置后的所有字符.
}
}
}
bool isvalid(string s)
{
if(s.at(0)=='0') return s=="0";
/*if(atoi(s.c_str())>255||atoi(s.c_str())<0)
return false;
else
return true;
*/
return atoi(s.c_str())<=255&&atoi(s.c_str())>0;
}
};
1 加边界检查 if (s.size()<4||s.size()>12) return res;
2 substr函数的用法要熟悉
3 pos表示递归层次
4 i<4&&i<s.size()这个很重要
5 不能取与substr函数变量相同的变量名
http://blog.csdn.net/u011095253/article/details/9158449
- Leetcode Restore IP Address
- Leetcode: Restore IP Address
- [LeetCode] Restore IP Address
- LeetCode: Restore IP Address
- [leetcode] restore IP address
- leetcode Restore IP Address
- Leetcode Restore IP Address
- LeetCode:Restore IP Address
- [LeetCode] Restore IP Address [28]
- Leetcode(91) Restore IP Address
- Restore IP Address Leetcode Python
- leetcode restore ip address Java实现
- Restore IP address
- 5th IP address restore
- LeetCode: Restore IP Addresses
- LeetCode : Restore IP Addresses
- [LeetCode] Restore IP Addresses
- [LeetCode]Restore IP Addresses
- Cocos2dx-3.x触摸事件之实现人机交互(三)
- refind 0.10.3 配置文件refind.conf简单分析
- 魏则西事件之后,民营医疗的营销方式
- Jquery Md5加密-Jquery.md5.js
- Java之json和对象之间的相互转换
- Leetcode Restore IP Address
- JavaScript数组的高级用法-reduce和reduceRight详解
- android动画定义
- 从 ASP .NET 进行 Active Directory 域服务身份验证
- java-jni-01-Introduction
- HDU4069(未AC)
- STM32F1学习-时钟系统
- UVA - 10916 Factstone Benchmark
- HDOJ 5499 SDOI(典型的翻译题目,处理女生特殊情况的问题)