EASY java backtracking method


  • 0
    W
    public List<String> restoreIpAddresses(String s) {
        List<String> list=new  ArrayList<String>();
        if(s.length()<4||s.length()>12){
            return list;   
        }
        helper(list,s,"",0,0);
        return list;
    }
    
    public void helper(List<String> list,String s,String cur,int start,int count){
        if(count==4){
            if(start==s.length()){
                list.add(cur.substring(1,cur.length()));
            }
            return;
        }
        if(start>=s.length())
            return;
        helper(list,s,cur+"."+s.substring(start,start+1),start+1,count+1);
        if(start<s.length()-1&&Integer.parseInt(s.substring(start,start+2))>9){
            helper(list,s,cur+"."+s.substring(start,start+2),start+2,count+1);
        }
        if(start<s.length()-2&&Integer.parseInt(s.substring(start,start+3))>99&&Integer.parseInt(s.substring(start,start+3))<256){
            helper(list,s,cur+"."+s.substring(start,start+3),start+3,count+1);
        }
    }

Log in to reply
 

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