93. Restore IP Addresses

93. Restore IP Addresses


// Input: "25525511135"
// Output: ["255.255.11.135", "255.255.111.35"]



class Solution {
    public List<String> restoreIpAddresses(String s) {
      List<String> res = new ArrayList<>();
      
      // sanity check 
      if(s == null || s.length() > 12) return res;
      
      // dfs 
      dfs(res, s, "", 0);
      return res;
    }
    
    private void dfs(List<String> res, String s, String cur, int level){
      // base case : when the level is 4 and there is nothing left in string s
      if(level == 4 && s.length() == 0){
        res.add(cur.substring(0, cur.length() - 1)); // remove the prefix "."
        return;
      }else if(level == 4 || s.length() == 0){ 
        // only one conditon satisfies
        return;
      }else{
        // we do dfs,three cases:  take one number, take two numbers , take three numbers 
        
        // take one number 
        dfs(res, s.substring(1), cur + s.substring(0, 1) + ".", level + 1);
        // s.substring(1) means the string now is from index 1 to the end , inclusive 
        
        // take two numbers, check condition: example: 02 is not valid 
        if(s.charAt(0) != '0' && s.length() > 1){
          dfs(res, s.substring(2), cur + s.substring(0, 2) + ".", level + 1);
        }
        
        // take three numbers : check condition, the value of xxx is <= 255 
        if(s.charAt(0) != '0' && s.length() > 2 && Integer.valueOf(s.substring(0, 3)) <= 255 ){
          dfs(res, s.substring(3), cur + s.substring(0, 3) + ".", level + 1);
        }
      }
    }
}

 

  1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
  2. public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.

In case of string:

  • startIndex: inclusive
  • endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

 
  1. String s="hello";  
  2. System.out.println(s.substring(0,2));//he  

 

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

 

 

posted on 2018-08-28 20:07  猪猪&#128055;  阅读(102)  评论(0)    收藏  举报

导航