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)
将字串划分选出合适的ip地址(回溯),此记两种做法
1)迭代,三层循环嵌套,每层取出1-3位的子字串,在第三层中将符合条件的字串加入数组
2)递归,利用深度优先搜索,逐步取出1-3个子字串并递归剩余的字串
迭代方法
package soc;
//Restore IP Addresses
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class RIA {
public static List<String> restoreIpAddresses(String s) {
List<String> iplist = new ArrayList<String>();
if(s.length()<4)return iplist; //排除过短字串
String ip,ip1,ip2,ip3,ip4;
//使用先取后拼合成地址的原则
for(int i=1;i<4;i++){
ip1 = s.substring(0, i);
if(!isvalid(ip1))break;
for(int j=1;(j<4&&j<s.length()-i);j++){ //循环的判断条件中加入j<s.length()-i,防止截取子字串时越界
ip2 = s.substring(i,i+j);
if(!isvalid(ip2))break;
for(int k=1;(k<4&&k<s.length()-i-j);k++){
ip3 = s.substring(i+j,i+j+k);
ip4 = s.substring(i+j+k,s.length());
if((!isvalid(ip3)) || (!isvalid(ip4)))continue;
else {
ip="";
ip+=(ip1+"."+ip2+"."+ip3+"."+ip4);
}
iplist.add(ip);
}
}
}
return iplist;
}
public static boolean isvalid(String s){
if(s.length()>3)return false;
if(s.length()>1 && s.startsWith("0")) return false;
if(Integer.parseInt(s)<256) return true;
else return false;
}
public static void main(String[] args) throws IOException{
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String ip = read.readLine();
List<String> iplist = restoreIpAddresses(ip);
Iterator<String> ite = iplist.iterator();
for(;ite.hasNext();){
System.out.println(ite.next());
}
}
}