leetcode-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)

代码分析:

public class Solution {
//这里没有用到回溯;
//1、根据长度判断  2、 根据大小判断
    public List<String> restoreIpAddresses(String s) {
        List<String> list = new ArrayList<String>();
        String ret;
//这里的for循环,经典写法
        for(int a = 1; a <= 3;a++)
        for(int b = 1; b <= 3;b++)
        for(int c = 1; c <= 3;c++)
        for(int d = 1; d <= 3;d++)
        //判断总长度
        if(a+b+c+d == s.length()){
            //截取子字符串,不要管位数,只要管 0~255就行!!!
            //当要在字符串中找符合条件的子串,就要用到substring(begin ,end)!!!

     //还有split用法
            //valueOf 和parseInt的用法: 前者返回Integer ,后者返回 int
           Integer A = Integer.valueOf(s.substring(0,a));
           Integer B = Integer.valueOf(s.substring(a,a+b));
           Integer C = Integer.valueOf(s.substring(a+b,a+b+c));
           Integer D = Integer.valueOf(s.substring(a+b+c,a+b+c+d));
           if(A<=255&&B<=255&&C<=255&&D<=255) {
            //但是,toString,只能由类来操作,所以A B C D 都是Integer类型,这和cpp要区别
            //要想从String -> int ,首先valueOf(),然后int c = Integer.valueOf("10").intValue();
            if((ret = A.toString()+"."+B.toString()+"."+C.toString()+"."+D.toString()).length() == s.length()+3)
                list.add(ret);
           }
        }
       return list;
    }
}

posted @ 2016-04-24 13:18  wangb021  阅读(148)  评论(0编辑  收藏  举报