1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution { public List<String> restoreIpAddresses(String s) { List<String> addresses = new ArrayList<>(); StringBuilder tempAddress = new StringBuilder(); backtricking(s,addresses,tempAddress,0); return addresses; } private void backtricking(String input,List<String> address,StringBuilder tempAddress,int k){ if(k == 4 || input.length() == 0){ if(k == 4 && input.length() == 0){ address.add(tempAddress.toString()); } return; } for(int i = 0; i < 3 && i < input.length();i++){ if(i != 0 && input.charAt(0) == '0'){ break; } String part = input.substring(0,i+1); if(Integer.valueOf(part) <= 255){ if(tempAddress.length() != 0){ part = "." + part; } tempAddress.append(part); backtricking(input.substring(i+1),address,tempAddress,k+1); tempAddress.delete(tempAddress.length() - part.length(),tempAddress.length()); } }
} }
|