93. Restore IP Addresses

Posted 鱼与海洋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了93. Restore IP Addresses相关的知识,希望对你有一定的参考价值。

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)

分析: 主要是validate的问题。

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<>();
        String item = new String();
        dfs(res, item , 0 , s);
        return res;
    }

    public void dfs(List<String> res , String item, int deep , String s){
        if(deep == 3 && isValid(s)){
            res.add(item + s);
            return;
        }
        for(int i = 0 ; i < 3 && i < s.length() ; i++){
            String sub = s.substring(0 , i+1);
            if(isValid(sub)){
                dfs(res , item + sub + ".", deep+1, s.substring(i+1, s.length()));
            }
        }
        
    }
    public boolean isValid(String s){
        if(s.charAt(0) == ‘0‘)
            return s.equals("0");
        int num = Integer.parseInt(s);
        if(num > 0 && num < 255)
            return true;
            
        return false;
    }
}

 

以上是关于93. Restore IP Addresses的主要内容,如果未能解决你的问题,请参考以下文章

93. Restore IP Addresses

93. Restore IP Addresses

93. Restore IP Addresses

93. Restore IP Addresses

93. Restore IP Addresses

Leetcode 93. Restore IP Addresses