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)
This problem can be solved by bfs method
public class Solution { public ArrayList<String> restoreIpAddresses(String s) { ArrayList<String> result = new ArrayList<String>(); int len = s.length(); if(len >= 4 && len <= 12){ result = bfs(s); } return result; } public ArrayList<String> bfs(String s){ ArrayList<String> result = new ArrayList<String>(); Queue<PairStrings> tempResult = new LinkedList<PairStrings>(); tempResult.add(new PairStrings("", s)); for(int i = 0; i < 4; ++i){ Queue<PairStrings> temp = new LinkedList<PairStrings>(); while(tempResult.peek() != null){ PairStrings aPair = tempResult.poll(); String aString = aPair.s2; int len = aString.length(); if(len > 0){ for(int j = 1; j < 4 && j < len + 1; ++j){ String subs = aString.substring(0,j); if((len - j <= 3 * ( 3 - i)) && checkValidation(subs)){ PairStrings newPair = new PairStrings(aPair.s1 + "." + subs, aString.substring(j, len)); temp.add(newPair); } } } } tempResult = temp; } while(tempResult.peek() != null){ PairStrings finalPairs = tempResult.poll(); String finalString = finalPairs.s1; if(finalString.charAt(0) == '.') result.add(finalString.substring(1, finalString.length())); } return result; } public boolean checkValidation(String s){ boolean canAppend = false; if(s.length() != 0){ if(s.charAt(0) == '0') canAppend = (s.equals("0")); else{ int num = Integer.parseInt(s); canAppend = (num >= 0 && num <= 255); } } return canAppend; } } class PairStrings{ String s1; String s2; PairStrings(String s1, String s2){ this.s1 = s1; this.s2 = s2; } }
rewrite the above code in a simple way
public class Solution { public List<String> restoreIpAddresses(String s) { int len = s.length(); List<String> validIP = new ArrayList<String>(); if(len < 4 || len > 12) return validIP; dfs(s, "", validIP, 0); return validIP; } private void dfs(String s, String startIp, List<String> validIp, int rounds) { if(rounds == 3 && isValid(s)) // the last round validIp.add(startIp + s); else { for(int i = 1; i < 4 && i < s.length(); ++i) { String current = s.substring(0, i); if(isValid(current)) dfs(s.substring(i), startIp + current+".", validIp, rounds + 1); } } } private boolean isValid(String s){ if(s.charAt(0) == '0') return s.length() == 1; return s.length() <= 3 && Integer.parseInt(s) <= 255; } }