#题干
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
想法
这题乍一看很唬人,仔细看其实就是要返回这个string的几种划分情况,并且一定是划分成四块,同时要求每一块都是合法的ip地址即可
啥是合法的ip地址?
首先如果是三位数
必须大于0小于255
只有一位数的开头第一位可以是0
这就叫合法
于是就有很多办法
暴力遍历
或者遍历以后在回溯
很多方法
直接看代码
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;
}
}
}
class Solution {
static List<String> res;
public List<String> restoreIpAddresses(String s) {
res = new ArrayList<>();
//String s = "25525511135";
int[] temp = new int[4];
dfs(s, s.length(), 0, temp, 0);
return res;
}
private static void dfs(String s, int n, int index, int temp[], int index1){
if(index1 == 4){
String ss = String.valueOf(temp[0]);
for(int i=1; i<4; i++){
ss += ".";
ss += String.valueOf(temp[i]);
}
res.add(ss);
return;
}
else{
for(int i=1; i<=n-index; i++){
if(index1==3){
i=n-index;
if(i>3)
return;
}
temp[index1] = Integer.parseInt(s.substring(index, index+i));
String s1 = s.substring(index, index+1);
if(temp[index1]>=0 && temp[index1]<=255 && (i==1 || !s1.equals("0"))){
dfs(s, n, index+i, temp, index1+1);
}
if(temp[index1]>255){
return;
}
}
}
}
}
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<>();
char[] chars = new char[s.length() + 3];
if (s.length() >= 4 && s.length() <= 12) {
this.backTrace(result, 0, s, 0, chars, 0);
}
return result;
}
private void backTrace(List<String> result, int start, String s, int pos, char[] chars, int number) {
if (pos > start + 3 || start == s.length() || pos == chars.length) {
if (pos == start + 3 && start == s.length()) {
result.add(new String(chars));
}
return;
}
char c = s.charAt(start);
chars[pos] = c;
number = number * 10 + (c - '0');
if (number < 256) {
int dots = pos - start;
// do not add dot
if ((number != 0 || start == s.length() - 1) && (pos <= s.length() - 4 + (dots << 1))) {
// System.out.println(String.format("do not add dot: %d, %d", start, pos));
this.backTrace(result, start + 1, s, pos + 1, chars, number);
}
// add dot
if (pos < chars.length - 2) {
// System.out.println(String.format("add dot: %d, %d", start, pos));
chars[pos + 1] = '.';
this.backTrace(result, start + 1, s, pos + 2, chars, 0);
}
}
}
}