这道题不是很难,题目如下:
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
package test;
import java.util.ArrayList;
import java.util.List;
public class LC93Try1
{
public List<String> restoreIpAddresses(String s)
{
List<String> ret = new ArrayList<String>();
restoreIpAddresses1(s, 0, 0, "", ret);
return ret;
}
public void restoreIpAddresses1(String s, int start, int n, String t,
List<String> ret)
{
if (n == 4)
{
if (start == s.length())
{
ret.add(t);
}
return;
}
if(start>=s.length()){
return;
}
char c=s.charAt(start);
for (int i = 1; i < 4 && start+i<=s.length(); i++)
{
if(c=='0' && i>1){
break;
}
String st = s.substring(start, start + i);
if (i == 3)
{
int sn = Integer.valueOf(st).intValue();
if (sn > 255)
{
continue;
}
}
String t1="";
if(n==0){
t1=st;
}else{
t1=t + "." + st;
}
restoreIpAddresses1(s, start + i, n + 1,t1 , ret);
}
}
public static void main(String[] args)
{
LC93Try1 t = new LC93Try1();
String s="010010";
System.out.println(t.restoreIpAddresses(s));
}
}