Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example
Given "25525511135"
, return
[
"255.255.11.135",
"255.255.111.35"
]
Order does not matter.
public class Solution { /** * @param s the IP string * @return All possible valid IP addresses */ public ArrayList<String> restoreIpAddresses(String s) { // Write your code here ArrayList<String> result = new ArrayList<String>(); String line = ""; helper(result, line, 0, s, 0); return result; } public void helper(ArrayList<String> result, String line, int start, String s, int count){ if(count == 4){ if(start == s.length()){ line = line.substring(0, line.length() - 1); result.add(line); return; } else return; } for(int i = start + 1; i <= start + 3 && i <= s.length(); i++){ if(valid(s.substring(start, i))){ String new_line = line + s.substring(start, i) + "."; helper(result, new_line, i, s, count + 1); } } return; } public boolean valid(String s){ if(s.charAt(0) == '0' && s.length() > 1) return false; int temp = Integer.parseInt(s); return (temp >= 0 && temp <= 255); } }