Concise JAVA Solution


  • 0
    public List<String> restoreIpAddresses(String s) {
        List<String> ans =new ArrayList<String>();
        re(0,4,s,"",ans);
        return ans;
    }
    public void re(int start,int remain,String s,String tmp,List<String> ans)
    {
        if(remain==0) ans.add(tmp.substring(0,tmp.length()-1));
        for(int i=1;i<=3;i++)
        {
            if(s.length()-start-i>=remain-1&&s.length()-start-i<=(remain-1)*3&&cSI(s.substring(start,start+i))<=255)
            re(start+i,remain-1,s,tmp+s.substring(start,start+i)+".",ans);
        }
    }
    public int cSI(String s)
    {
        int num=0;
        if(s.length()>1&&s.charAt(0)=='0') return 256;
        for(int i=0;i<s.length();i++) num=num*10+s.charAt(i)-'0';
        return num;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.