首页 > 其他 > 详细

leetcode 93-Restore IP Addresses(medium)

时间:2018-09-23 11:08:00      阅读:40      评论:0      收藏:0      [点我收藏+]

标签:tput   nbsp   cas   ble   bound   address   com   bst   style   

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

 

IP address is consist of 4 parts with each part among (0,255)

so every part can be consist of 1, 2 or 3 digits, and the leading one shouldn‘t be zero.

cases:

1. already get 4 parts and index come to the end of the string, add string to the list and return;

2. s.charAt(index)==‘0‘, only one case is valid, that is, this part is "0";

3. iterate through index->index+1, index->index+2, index->index+3 digits, judge whether it is a valid part, if it is, add it to the string, and continue dbp.

 

class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> list=new ArrayList<>();
        if(s.length()<4) return list;
        findIP(s, list, "", 0, 0);
        return list;
    }
    
    public void findIP(String s, List<String> list, String str, int index, int part){
        if(part==4||index==s.length()){
            if(part==4&&index==s.length()) list.add(str.substring(1));
            return;
        } 
        if(s.charAt(index)==‘0‘){
            findIP(s, list, str+".0", index+1, part+1);
        }
        else{
            for(int i=1;i<4;i++){
                if(index+i<=s.length()&&Integer.parseInt(s.substring(index,index+i))<256){
                    findIP(s,list, str+"."+s.substring(index,index+i),index+i, part+1);
                }
            }
        } 
    }
}

 

注意:所有需要取无论数组还是string的某几位的时候,都要注意是否会out of bound, for循环中的变量i往往不需要担心,主要对于while循环之类其他的地方自己定义的一个循环变量或者其他值加上循环变量后产生的新的量是否会超过bound,很容易忽视,一定要小心!截取或抽取的时候一定要考虑一下会不会超出范围。比如这道题先就忘了index+i会超出s范围。

leetcode 93-Restore IP Addresses(medium)

标签:tput   nbsp   cas   ble   bound   address   com   bst   style   

原文:https://www.cnblogs.com/yshi12/p/9691888.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号