Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<>();
addResult(res, s, 0, 1, "");
return res;
}
void addResult(List<String> res,String s,int begin,int segment,String tmp) {
if(segment >5) {
return;
}
if(begin == s.length() && segment==5) {
res.add(tmp.substring(0,tmp.length()-1).toString());
return;
}
//当前段为长度i
for(int i=1;i<=3;i++) {
if(begin+i > s.length()) {
return ;
}
if(s.charAt(begin)=='0' && i>1) {
return ;
}
if(Integer.valueOf(s.substring(begin, begin+i)) > 255) {
return ;
}
String tmpV = s.substring(begin, begin+i)+".";
tmp+=tmpV;
addResult(res,s,begin+i,segment+1,tmp);
tmp=tmp.substring(0, tmp.length()-tmpV.length());
}
}
}
把每段进行遍历,符合一定条件