描述
现在有一个只包含数字的字符串,将该字符串转化成IP地址的形式,返回所有可能的情况。
例如:
给出的字符串为"25525522135",
返回["255.255.22.135", "255.255.221.35"]. (顺序没有关系)
数据范围:字符串长度 0≤n≤120 \le n \le 120≤n≤12
要求:空间复杂度 O(n!)O(n!)O(n!),时间复杂度 O(n!)O(n!)O(n!)
注意:ip地址是由四段数字组成的数字序列,格式如 "x.x.x.x",其中 x 的范围应当是 [0,255]。
示例1
输入:
"25525522135"
返回值:
["255.255.22.135","255.255.221.35"]
示例2
输入:
"1111"
返回值:
["1.1.1.1"]
示例3
输入:
"000256"
返回值:
"[]"
import java.util.ArrayList;
public class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
ArrayList<String> result = new ArrayList<>();
int length = s.length();
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
for (int m = 1; m <= 3; m++) {
for (int n = 1; n <= 3; n++) {
if (i + j + m + n == length) {
String one = s.substring(0, i);
String two = s.substring(i, i+j);
String three = s.substring(i+j, i+j+m);
String four = s.substring(i+j+m, i+j+m+n);
if ((Integer.valueOf(one) >= 0 && Integer.valueOf(one) <= 255) && (Integer.valueOf(two) >= 0 && Integer.valueOf(two) <= 255) && (Integer.valueOf(three) >= 0 && Integer.valueOf(three) <= 255) && (Integer.valueOf(four) >= 0 && Integer.valueOf(four) <= 255)) {
if (one.length() == 1 || one.charAt(0) != '0')
if (two.length() == 1 || two.charAt(0) != '0')
if (three.length() == 1 || three.charAt(0) != '0')
if (four.length() == 1 || four.charAt(0) != '0')
result.add(one+"."+two+"."+three+"."+four);
}
}
}
}
}
}
return result;
}
}