restore-ip-addresses
来源:互联网 发布:微信 for windows 编辑:程序博客网 时间:2024/06/15 17:06
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)
这个题太复杂了
利用dfs;
这棵树是一个三叉树,ip地址前三段确定之后最后一段就确定了不再是三叉树,所以要把第三段和最后一段一起考虑.
class Solution {public: vector<string> restoreIpAddresses(string s) { if(s.size()<4||s.size()>12) return vector<string>{}; vector<string> res; string tmp; recurbuild(res,s,0,tmp,0,s.size()); return res; } void recurbuild(vector<string>& res,string &s,int begin,string &tmp,int count,int limit) { string str=tmp; //保留上一层路径的节点 if(count==0){ for(int i=1;i<=3;++i){ if(i==1||i>1&&s[begin]!='0'&&atoi(s.substr(begin,i).c_str())<=255){ tmp+=s.substr(begin,i); tmp+='.'; recurbuild(res,s,begin+i,tmp,count+1,limit-i); tmp=str; //还原 } } } else if(count==1&&limit>=3&&limit<=9) { for(int i=1;i<=3;++i){ if(i==1||i>1&&s[begin]!='0'&&atoi(s.substr(begin,i).c_str())<=255){ tmp+=s.substr(begin,i); tmp+='.'; recurbuild(res,s,begin+i,tmp,count+1,limit-i); tmp=str; } } } else if(count==2&&limit>=2&&limit<=6) { for(int i=1;i<=min(3,limit-1);++i){ if(i==1||i>1&&s[begin]!='0'&&atoi(s.substr(begin,i).c_str())<=255){ if(s[begin+i]=='0'&&s.size()-begin-i>1||s.size()-begin-i>3||atoi(s.substr(begin+i,s.size()-begin-i).c_str())>255) continue; tmp+=s.substr(begin,i); tmp+='.'; tmp+=s.substr(begin+i,s.size()-begin-i); res.push_back(tmp); tmp=str; } } } }};
0 0
- LeetCode: Restore IP Addresses
- Restore IP Addresses
- LeetCode : Restore IP Addresses
- [LeetCode] Restore IP Addresses
- Restore IP Addresses
- [LeetCode]Restore IP Addresses
- Restore IP Addresses
- Restore IP Addresses
- LeetCode:Restore IP Addresses
- Restore IP Addresses
- Restore IP Addresses
- LeetCode Restore IP Addresses
- [leetcode] Restore IP Addresses
- Restore IP Addresses
- LeetCode:Restore IP Addresses
- [LeetCode] Restore IP Addresses
- LeetCode - Restore IP Addresses
- LeetCode | Restore IP Addresses
- opencv(5)---绘图函数
- ZOJ2417&&HDU1196-Lowest Bit
- oracle数据类型和对应的java类型
- 阿里云faq
- Android解压system.img
- restore-ip-addresses
- 数据结构复习笔记 3
- C++起航篇——bool类型,输入输出,命名空间
- 友盟社会化分享微信登录签名错误
- 如何改变文件属性与权限
- 《属灵操练礼赞》读后感
- thinkphp5,tpshop5下的数据库查询构造器的思考
- 文章标题
- 使用JsonView来格式化json字符串