Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 25, 2015 09:29
Show Gist options
  • Save charlespunk/6954876 to your computer and use it in GitHub Desktop.
Save charlespunk/6954876 to your computer and use it in GitHub Desktop.
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)
public class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ArrayList<String> output = new ArrayList<String>();
parse(s, 0, 0, true, 0, new int[4], output);
return output;
}
public void parse(String s, int pos, int last, boolean start, int temp_index, int[] temp, ArrayList<String> output){
if(pos == s.length()){
if(temp_index == temp.length && start){
output.add(temp[0] + "." + temp[1] + "." + temp[2] + "." + temp[3]);
}
return;
}
if(temp_index == temp.length) return;
if(last == 0 && !start){
temp[temp_index] = 0;
parse(s, pos, 0, false, temp_index + 1, temp, output);
}
else{
int now = last * 10 + s.charAt(pos) - 48;
if(now > 255) return;
//stop here
temp[temp_index] = now;
parse(s, pos + 1, 0, true, temp_index + 1, temp, output);
//mach to next pos
parse(s, pos + 1, now, false, temp_index, temp, output);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment