题目描述:
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
中文理解:
给定一个字符串,将这个字符串左右可能组成的ip地址组成都返回。
解题思路:
首先进行一场情况考虑,如果字符串的长度小于4或者大于12,直接返回空的列表,如果等于4或者12,也可直接返回四等分的数列,同时判断12位情况下,每个三位是否满足在0-255之间。其他情况下,可以使用递归来进行解决。
代码(java):
class Solution {
public List<String> restoreIpAddresses(String string) {
List<String> res = new LinkedList<>();
if (string == null || string.length() < 4 || string.length() > 12) return res;
if (string.length() == 4) {
String s = "";
for (Character c : string.toCharArray()) s = s + c + ".";
res.add(s.substring(0, s.length() - 1));
return res;
}
helper(string, res, "", 0, 0);
return res;
}
private void helper(String string, List<String> res, String tmpS, int count, int index) {
if (index == string.length() && count == 4) {
res.add(tmpS.substring(0, tmpS.length() - 1));
return;
}
if (count >= 4 || index >= string.length()) return;
for (int i = index; i < string.length(); i++) {
long tmp = Long.valueOf(string.substring(index, i + 1));
//进行0开头的数值剔除,比如01会被删除,因为01转换为整数是1,同时1转换为字符串长度为1,与原先的01长度不等
if (tmp >= 0 && tmp <= 255 && String.valueOf(tmp).length() == string.substring(index, i + 1).length()) {
helper(string, res, tmpS + tmp + ".", count + 1, i + 1);
}
}
}
}