https://leetcode.com/problems/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)
即,当某层递归的start处是一个'0'字符的话,它这层只能变成'0',而不能再和后面的数字组合变成如'02'之类的了。
我传递的ip string,感觉如果传递arraylist<String>,最后再造一个ip string的话可能会快一些。
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> rst = new LinkedList<String>();
if(s==null || s.length()==0) return rst;
String ip = "";
helper(s, 0, rst, ip, 0);
return rst;
}
public void helper(String s, int start, List<String> rst, String ip, int count){
if(start == s.length() && count==4){
rst.add(ip.substring(0, ip.length()-1));
return;
}
else if(start==s.length() || count>=4) return;
if(s.charAt(start)=='0'){
ip = ip+"0";
ip = ip+'.';
helper(s, start+1, rst, ip, count+1);
ip = ip.substring(0, ip.length()-2);
}
else{
for(int i= start; i<start+3 && i<s.length(); i++){
String sub = s.substring(start, i+1);
int val = Integer.parseInt(sub);
if(val>=0 && val<=255){
ip = ip+sub;
ip = ip + ".";
helper(s, i+1, rst, ip, count+1);
ip = ip.substring(0, ip.length()-sub.length()-1);
}
}
}
}
}