• 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"]


    原来的思路:
        //这里不是从1开始的,是从start开始的,然后i最多等于start + 3.
        //backtrace中,start递归换成i + 1
        for (int sectionLength = 1; sectionLength < 4; sectionLength++) {
            if (isValid())
        }

    应该有的思路:其实不用纠结什么字符串长度123,保证每一截都是有效的就行了。head这一截和剩下的部分

    控制remainingCount从4开始即可。

    退出条件:s.length() == 0,不是s == ""

    从1到最后一位,因为取head的时候需要包括在内
    for (int i = 1; i <= s.length(); i++)

    head是valid就回溯,不行就break

    判断第一位是否等于0的方法:看看字符串长度和数字长度是否相等

    s.length() == String.valueOf(val).length()
    class Solution {
        //右边需要初始化
        List<String> results = new ArrayList<>();
        
        public List<String> restoreIpAddresses(String s) {
            //cc
            if (s.length() == 0) 
                return results;
            
            backtrace(s, "", 4);
            
            return results;
        }
        
        public void backtrace(String s, String currentString, int remainingCount) {
            //exit
           if (s.length() == 0 && remainingCount == 0) {
               results.add(currentString.substring(0, currentString.length() - 1));
               return ;
           }
            
            if (s.length() == 0 || remainingCount == 0) 
                return ;
            
            for (int i = 1; i <= s.length(); i++) {
                String head = s.substring(0, i);
                
                if (isValid(head)) {
                    backtrace(s.substring(i), currentString + head + ".", 
                             remainingCount - 1);
                }else break;
            }
            
        }
        
        private boolean isValid(String s) {
        int val = Integer.valueOf(s);
        if (val > 255) return false;
        return s.length() == String.valueOf(val).length();
    }
    }
    View Code
     
  • 相关阅读:
    【十大思想实验之中的一个】电车难题
    XMLHTTP使用具体解释
    高速排序 解析
    RapeLay(电车之狼R)的结局介绍 (隐藏结局攻略)
    java设计模式演示样例
    [Network]Transport Layer
    【2012.1.24更新】不要再在网上搜索eclipse的汉化包了!
    WebService究竟是什么?
    epoll使用具体解释(精髓)
    贪心算法
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13368618.html
Copyright © 2020-2023  润新知