题解 | #数字字符串转化成IP地址#
数字字符串转化成IP地址
http://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
//给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
//输入: "25525511135"
//输出: ["255.255.11.135", "255.255.111.35"]
class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
ArrayList<String> result = new ArrayList<>();
if(s==null || s.length() < 4 || s.length()>12){
return result;
}
for (int i = 1; i < 5; i++) {
String ip1 = s.substring(0, i);
if(!checkLegal(ip1)) continue;
for (int j = i+1; j < Math.min( s.length(), i+5); j++) {
String ip2 = s.substring(i, j);
if(!checkLegal(ip2)) continue;
for (int k = j+1; k < Math.min( s.length(), j+5); k++) {
String ip3 = s.substring(j, k);
if (!checkLegal(ip3)) continue;
String ip4 = s.substring(k);
if (!checkLegal(ip4)) continue;
result.add(ip1 + "." + ip2 +"."+ ip3+"."+ip4);
}
}
}
return result;
}
private boolean checkLegal(String s){
if(s.isEmpty() || s.length()>3) return false;
if(!"0".equals(s) && s.startsWith("0")) return false;
int ip = Integer.parseInt(s);
return ip>=0 && ip <= 255;
}
}