您的位置:首页 > 其它

Leetcode: Restore IP Addresses

2014-11-05 07:53 399 查看
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)
Start from the first character in the string, and check whether sub
strings starting from that character to at most 2 following characters are less than 255. Note that sub strings whose length are longer than 1 but starting with 0 are also not valid. If they are valid, add a dot, and keep checking the next sub strings while
there are no more than 3 dots. Add the ip addresses to the result only when there are 3 dots and the last sub string happen to be valid.

public class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
ArrayList<String> res = new ArrayList<String>();
if (s == null || s.length() == 0) {
return res;
}

StringBuilder ip = new StringBuilder();
helperIp(s, res, ip, 0, 0);
return res;
}

private void helperIp(String s, ArrayList<String> res, StringBuilder ip, int pos, int count) {
if (count == 4 && pos == s.length()) {
ip.deleteCharAt(ip.length() - 1);
res.add(ip.toString());
return;
}

if (count == 4 && pos < s.length()) {
return;
}

for (int i = 1; i <= 3; i++) {
if (i > 1 && s.charAt(pos) == '0') break;
if (pos + i > s.length()) break;
String sub = s.substring(pos, pos + i);
int num = stringToInteger(sub);
if (num <= 255) {
ip.append(sub);
ip.append('.');
helperIp(s, res, ip, pos + i, count + 1);
ip.delete(pos + count, ip.length());
} else {
break;
}
}
}

private int stringToInteger(String s) {
int num = 0;
for (int i = 0; i < s.length(); i++) {
num = num * 10 + (s.charAt(i) - '0');
}

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