Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135"
,
return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)
这道题不太会写,主要是for循环的位置总是卡住,再写的时候注意一下。
Integer.valueOf(String s)返回值为Integer类型,Integer.parseInt(String s)返回值是int类型,二者都是把string转换为整型数据。此题在转换前一定要注意判断是否是诸如002这种不符合的形式,否则转换完就默认为有效数据了。
Source
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> st = new ArrayList<String>();
String a = new String();
if(s.length() < 4 || s.length() > 12) return st;
int area = 1;
dfs(area, s, st, a);
return st;
}
public boolean isValid(String s){
if(s.charAt(0) == '0'){
if(s.equals("0")) //如果第一位为0 则判断整体是否为字符串“0” 如002这种就是无效数据
return true;
else return false;
}
int num = Integer.valueOf(s);
if(num >=0 && num <= 255) //***
return true;
else return false;
}
public void dfs(int area, String s, List<String> st, String a){
if(area == 4 && isValid(s)){
a = a + s;
st.add(a);
return ;
}
for(int i = 1; i <= 3; i++){
String temp;
if(s.length() >= i)
temp = s.substring(0, i);
else return;
if(isValid(temp) && i < s.length())
dfs(area + 1, s.substring(i, s.length()), st, a + temp + ".");
//注意substring的end 截取时不包含end位置的字符,只截取到end-1的位置
}
}
}
Test
public static void main(String[] args){
String s = "25525511135";
List<String> a = new Solution().restoreIpAddresses(s);
System.out.println(a);
}