码迷,mamicode.com
首页 > 其他好文 > 详细

Restore IP Addresses

时间:2014-09-10 10:52:10      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:leetcode   algorithm   

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ mn ≤ length of list.

答案

public class Solution {
    int LEN;
    public List<String> getRemainingString(String s,int position,int index){
        int len=0;
        List<String> result=new LinkedList<String>();
        String subString;
        if(index==3)
        {
            subString=s.substring(position);
            int p=Integer.parseInt(subString);
            if(p>=0&&p<=255){
                if(!(subString.length()>1&&subString.startsWith("0"))){
                    result.add(subString);
                }
            }
            return result;
        }
        int maxLEN=Math.min(3,LEN-position-(3-index));
        for(len=1;len<=maxLEN;len++){
            subString=s.substring(position,position+len);
            int p=Integer.parseInt(subString);
            if(p>=0&&p<=255){
                 if(!(subString.length()>1&&subString.startsWith("0"))){
                    result.add(subString);
                }
            }
        }
        return result;
    }
    public List<String> parseIP(String s,int position,int index)
    {
        List<String> result=new LinkedList<String>();
        List<String>p=getRemainingString(s,position,index);
        if(index==3){
            return p;
        }
        for(String current:p)
        {
            List<String>t=parseIP(s,position+current.length(),index+1);
            for(String next:t)
            {
                result.add(current+"."+next);
            }
        }
        return result;
    }
    public List<String> restoreIpAddresses(String s) {
        if(s==null||s.length()<4||s.length()>12){
            return new LinkedList<String>();
        }
        LEN=s.length();
        return parseIP(s,0,0);
    }
}


Restore IP Addresses

标签:leetcode   algorithm   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39178107

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!