zoukankan      html  css  js  c++  java
  • 93. Restore IP Addresses 93.恢复IP地址

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

    A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.

    Example:

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

    思路:DFS是分成四个部分 又是剩下的继续分的思路。怎么选择end的位数啊?1、2、3位都要选吗?是的呢。
    for循环的字符串长度和section的增加都在DFS中完成
    generateIpAddresses(s, sec + 1, currentLength + i,
    
    

    添加完就行了,加个return ;

    
    
            if (sec == 4 && currentLength == s.length()) {
                result.add(curIP);
                return ;
            }
    
    
    class Solution {
        public List<String> restoreIpAddresses(String s) {
            List<String> result = new ArrayList<>();
            
            //cc
            if (s == null || s.length() == 0)
                return  result;
            
            //dfs, add to a List<String>, return void
            dfs(s, 0, 0, "", result);
            
            //return
            return result;
        }
        
        public void dfs(String s, int sec, int currentLength, String currentIP, 
                               List<String> result) {        
            //exit
            if (sec > 4)
                return ;
            
            if (sec == 4 && currentLength == s.length()) {
                result.add(currentIP);
                return ;
            }
            
            for (int i = 1; i <= 3; i++) {
                //cc
                if (currentLength + i > s.length())
                    return;
                
                String sectionIP = s.substring(currentLength, currentLength + i);
                
                if ((sectionIP.length() > 1 && sectionIP.charAt(0) == '0') || 
                    (Integer.valueOf(sectionIP) > 255))
                    break;
                
                dfs(s, sec + 1, currentLength + i, 
                    currentIP == "" ? sectionIP: currentIP + "." + sectionIP, 
                    result);
            }
        }
    }
    View Code

  • 相关阅读:
    xwalkview 替换掉webview 注意事项
    rsyslog Properties 属性:
    Basic Structure 基本结构:
    Crosswalk 集成到 Android Studio
    awk if 判断
    Important System Configuration 导入系统配置:
    Heap size check 堆大小检查
    Bootstrap Checks 抽样检查:
    Important Elasticsearch configuration 导入Elasticsearch 配置
    while 退出循环
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13287044.html
Copyright © 2011-2022 走看看