题干
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 ‘.’ 分隔。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
想法
枚举
没用完所有字数的不合法
数字不在0和255区间内的不合法
一定分为四块
Java代码
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res=new ArrayList<>();
//递归函数
helper(s,4,"",res);
return res;
}
//递归函数 s是操作的s,num是待解决的子网掩码的个数,out是递归出,res是存最后结果
public void helper(String s,int num,String out,List<String> res){
if(num==0){
if(s.isEmpty()){
res.add(out);
}
}
else{
//对每个子网掩码 从0位到三位
for(int index=0;index<4;index++){
if(s.length()>=index&&isValid(s.substring(0,index))){
//若是还剩一位 就别加.了
if(num==1){
helper(s.substring(index),num-1,out+s.substring(0,index),res);
}
else{
helper(s.substring(index),num-1,out+s.substring(0,index)+".",res);
}
}
}
}
}
public boolean isValid(String s) {
if (s.isEmpty() || s.length() > 3 || (s.length() > 1 && s.charAt(0) == '0')) {
return false;
} else {
int resInt = Integer.parseInt(s);
return resInt <= 255 && resInt >= 0;
}
}
}