Example:
Input: “25525511135”
Output: [“255.255.11.135”, “255.255.111.35”]
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> list = new ArrayList();
if(s.length() > 12) return list;
helper(s, list, 0, "", 0);
return list;
}
void helper(String s, List<String> list, int pos, String res, int sec){
if(sec == 4 && pos == s.length()) {
list.add(res);
return;
}
for(int i = 1; i <= 3; i++){
if(pos + i > s.length()) break;
String section = s.substring(pos, pos + i);
if(section.length() > 1 && section.startsWith("0") || Integer.parseInt(section) >= 256) break;
helper(s, list, pos + i, sec == 0 ? section : res + "." + section, sec + 1);
}
}
}