描述 :
给一个由数字组成的字符串。求出其可能恢复为的所有IP地址。
样例;
给出字符串 "25525511135"
,所有可能的IP地址为:
[
"255.255.11.135",
"255.255.111.35"
]
(顺序无关紧要)
思路:
两个计数指针,一个计数执行到字符串的第几位,一个计数执行到IP的第几位,要判断value<256并且首位不能为0
public class Solution {
/**
* @param s the IP string
* @return All possible valid IP addresses
*/
public ArrayList<String> restoreIpAddresses(String s) {
// Write your code here
ArrayList<String> result = new ArrayList<String>();
String temp = new String();
search(s , temp , result , 4 , 0 , s.length());
return result;
}
public void search(String s , String temp , ArrayList<String> result , int count , int index , int len){
//index 操作到字符串第几个字符
//count 操作到IP第几位
if(count == 0 && index == len){
result.add(temp);
return ;
}
if((count == 0 && index < len) || (count > 0 && index == len)){
return ;
}
int value = 0;
boolean flag = true;//第一个字符是否为0标志
while(index < len && flag){
if(value == 0 && s.charAt(index) == '0'){
flag = false;
}
value = value * 10 + s.charAt(index) - '0';
index++;
if(value < 256){
String record = "";
if(count == 1){
record = temp + Integer.toString(value);
}else{
record = temp + Integer.toString(value) + '.';
}
search(s , record , result , count - 1 , index , len);
}
}
}
}