标签:
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)
解题思路:
使用循环即可解决,JAVA实现如下:
static public List<String> restoreIpAddresses(String s) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 3; i++)
for (int j = i + 2; j < i + 5&&j<=s.length()-2; j++)
for (int k = j + 1; k < j + 4&&k<=s.length()-1; k++){
if (isValid(s.substring(0, i + 1))
&& isValid(s.substring(i + 1, j))
&& isValid(s.substring(j, k))
&& isValid(s.substring(k, s.length())))
list.add(s.substring(0, i + 1) + "."
+ s.substring(i + 1, j) + "."
+ s.substring(j, k) + "."
+ s.substring(k, s.length()));
}
return list;
}
public static boolean isValid(String s) {
if (s.length()>3)
return false;
int num = Integer.parseInt(s);
return num <= 255 && (num + "").equals(s);
}
Java for LeetCode 093 Restore IP Addresses
标签:
原文地址:http://www.cnblogs.com/tonyluis/p/4518358.html