Leetcode-Resotre IP Addresses
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)
Analysis:
This is a recursive problem. A string will be divided into four parts. For each part, we should determine whether it is a valid IP segment.
Solution:
1 public class Solution { 2 public List<String> restoreIpAddresses(String s) { 3 List<String> res = new ArrayList<String>(); 4 if (s.length()==0) return res; 5 6 res = restoreRecur(s,0,4); 7 return res; 8 } 9 10 public List<String> restoreRecur(String s, int curIndex, int num){ 11 List<String> res = new ArrayList<String>(); 12 if (curIndex>=s.length()) return res; 13 14 if (num==1){ 15 String temp = s.substring(curIndex,s.length()); 16 if (temp.length()>3) return res; 17 int val = Integer.parseInt(temp); 18 if (temp.length()==3 && val>=100 && val<=255){ 19 res.add(temp); 20 return res; 21 } 22 if (temp.length()==2 && val>=10 && val<=99){ 23 res.add(temp); 24 return res; 25 } 26 if (temp.length()==1){ 27 res.add(temp); 28 return res; 29 } 30 return res; 31 } 32 33 if (curIndex+1>=s.length()) return res; 34 int end = curIndex+3; 35 if (curIndex+3>s.length()) 36 end = s.length(); 37 38 39 for (int i=curIndex+1;i<=end;i++){ 40 String temp = s.substring(curIndex,i); 41 int val = Integer.parseInt(temp); 42 List<String> nextRes = new ArrayList<String>(); 43 if (temp.length()==3 && val>=100 && val<=255){ 44 nextRes = restoreRecur(s,i,num-1); 45 } 46 if (temp.length()==2 && val>=10 && val<=99){ 47 nextRes = restoreRecur(s,i,num-1); 48 } 49 if (temp.length()==1){ 50 nextRes = restoreRecur(s,i,num-1); 51 } 52 for (int j=0;j<nextRes.size();j++) 53 res.add(temp+"."+nextRes.get(j)); 54 } 55 return res; 56 57 } 58 }