您的位置:首页 > 其它

Restore IP Addresses

2014-12-25 15:21 190 查看
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,2,3位 一共由4组组成 每组的大小为0-255 要注意的是数字组成的合法性 001,01这样的是不合法的 要去除掉 代码如下:

public class Solution {

public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<String>();
ipformat(res, "", "", s, 0, 0, 1, 0);
ipformat(res, "", "", s, 0, 0, 2, 0);
ipformat(res, "", "", s, 0, 0, 3, 0);
return res;
}

public void ipformat(List<String> res, String tmp, String sip,
String s, int index, int count, int slen, int num) {
if (index == s.length() || num == 4) {
if (tmp.length() - 4 == s.length()) {
String ss="";
for(int i=0;i<tmp.length()-1;i++){
ss+=tmp.charAt(i);
}
res.add(ss);
}
return;
}
if(slen>=2&&count!=0){
if(sip.charAt(0)=='0') return;
}
if (count == slen - 1) {
int flag = 0;
if (slen <= 2) {
flag = 1;
} else {
int com = 0;
for (int j = 0; j < slen - 1; j++) {
com = (sip.charAt(j) - '0') + com * 10;
}
com = com * 10 + s.charAt(index) - '0';
if (com <= 255&&com>0) {
flag = 1;
}
}
if (flag == 1) {
if (index == s.length() - 1) {
ipformat(res, tmp + sip + s.charAt(index) + '.', "", s,
index + 1, 0, 1, num + 1);
} else {
ipformat(res, tmp + sip + s.charAt(index) + '.', "", s,
index + 1, 0, 1, num + 1);
ipformat(res, tmp + sip + s.charAt(index) + '.', "", s,
index + 1, 0, 2, num + 1);
ipformat(res, tmp + sip + s.charAt(index) + '.', "", s,
index + 1, 0, 3, num + 1);
}
}
} else {
ipformat(res, tmp, sip + s.charAt(index), s, index + 1, count + 1,
slen, num);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  backtracting