[leetcode.com]算法题目 - Restore IP Addresses
2024-10-20 20:58:43
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)
我的答案如下:
class Solution {
public: vector<string> restoreIpAddresses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i=,j,k;
int len = s.size();
vector<string> result;
if (len> || len< )
return result;
for(i;i<len-;i++){
for(j=i+;j<len-;j++){
for(k=j+;k<len-;k++){
string s1 = s.substr(,i+);
string s2 = s.substr(i+,j-i);
string s3 = s.substr(j+,k-j);
string s4 = s.substr(k+);
if(isOK(s1) && isOK(s2) && isOK(s3) && isOK(s4)){
string s5 = s1 + "." + s2 + "." + s3 + "." + s4;
result.push_back(s5);
}
}
}
}
return result;
} bool isOK(string s){
int len = s.size();
if (len> || len <)
return false;
else if (==len)
return true;
else if (==len){
return (''!=s.at());
}else{//3==len
int a = (s.at()-'')* + (s.at()-'')*+(s.at()-'');
return (a>= && a<=);
}
}
};
我的答案
思路:遍历所有的可能性,因为最多也就是个长度为12的字符串,三层循环也不用考虑复杂度的问题。把parse出来的三个string检查一下是否为0至255之间的整数,如果四个都满足,那就是这个题目的一个解。主要首位数不能为0,例如03,012这样的不算是在0至255之间。
最新文章
- hibernate处理null 时提示:Property path [...] does notreference a collection
- javascript获取当前时间
- python3.4安装suds
- android 点击重新加载界面设计
- servlet简介
- leetcode算法刷题(二)——动态规划(一)
- Ajax请求URL后加随机数原理
- 推荐几个靠谱的VPN
- iOS 断点上传文件
- [国嵌笔记][006][Linux文本编辑器]
- ORACLE中修改表的Schema的总结
- Oracle技术面试问题
- noip2011 玛雅游戏 大模拟
- 一篇文章彻底搞懂es6 Promise
- Go-延时函数defer
- Unity3D|-XLua热更新用法的大致流程
- appium:运行脚本时,报404的解决办法
- 修改input 的 placeholder
- 本地Debug Asp.net MVC 无法加载css与js
- django403错误(转)