【LeetCode】93.Restore IP Addresses(medium)解题报告
题目地址:https://leetcode.com/problems/restore-ip-addresses/description/
题目描述:
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)可以用backtracking方法做,也可以三层for循环,但是三层循环边界条件较多。面试出现频率较低。
Solution1:
//time:O(3^4) = O(n)
//space:O(n)
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<>();
helper(res,s,0,"",0);
return res;
}
public void helper(List<String> res,String s,int index,String ret,int count){ //ret存结果
if(count>4) return;
if(count==4 && index==s.length()){
res.add(ret);
return;
}
for(int i=1 ; i<4 ; i++){
if(index + i > s.length()) break; //越界
String temp = s.substring(index,index+i);
if((temp.startsWith("0") && temp.length()>1) || (i == 3 && Integer.parseInt(temp)>=256)) continue;
helper(res,s,index+i,ret+temp+(count==3?"":"."),count+1);
}
}
}
Solution2:
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<String>();
int len = s.length();
for(int i = 1; i<4 && i<len-2; i++){
for(int j = i+1; j<i+4 && j<len-1; j++){
for(int k = j+1; k<j+4 && k<len; k++){
String s1 = s.substring(0,i), s2 = s.substring(i,j), s3 = s.substring(j,k), s4 = s.substring(k,len);
if(isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4)){
res.add(s1+"."+s2+"."+s3+"."+s4);
}
}
}
}
return res;
}
public boolean isValid(String s){
if(s.length()>3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s)>255)
return false;
return true;
}
}
Date:2018年1月16日