leetcode 93. Restore IP Addresses

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


思路:dfs,特别注意首位为0的情况,和添加地址符号 "."  和判断下面3个数的值小于256的情况。


class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> list=new ArrayList<>();
        dfs(s,0,0,list,new StringBuilder());
        return list;
    }
    public void dfs(String s,int index,int count,List<String> list,StringBuilder sb){
        if(index>=s.length()&&count==4){
            list.add(sb.substring(0,sb.length()-1));
        }else if(index<s.length()&&count==4){
            return;
        }
        for(int i=index,num=0;i<s.length()&&i<index+3;i++){
            num=num*10+s.charAt(i)-'0';
            if(!(i!=index&&s.charAt(index)-'0'==0)&&num<256){//排除首位为0时,后面位还存在数的情况
                sb.append(s.substring(index,i+1)+".");
                dfs(s,i+1,count+1,list,sb);
                sb.delete(sb.length()-(i+2-index),sb.length());
            }
            
        }
    }
}


阅读更多
个人分类: leetcode and lintcode
上一篇leetcode 95. Unique Binary Search Trees II
下一篇leetcode 72. Edit Distance
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭