JAVA beat 95% ez and clean


  • 0
    D
    private List<String> res;
    
    public List<String> restoreIpAddresses(String s) {
        res = new ArrayList<String>();
        String curr = "";
        dfs(s,curr,-1,0);
        return res;
        
    }
    
    public void dfs(String s,String curr, int idx, int len){
        if(len == 4 && idx == s.length()-1){
            res.add(curr.substring(0,curr.length()-1));
            return;
        }
        int temp = 0;
        if(s.length()-1-idx>3*(4-len))      // judgement
            return;
        for(int i = 1;i<=3;i++){
            if(idx+i >= s.length()) break;
            
            if(i==1 && s.charAt(idx + 1) == '0'){   // begin with 0
                dfs(s,curr + "0.",idx + 1,len +1 );
                break;
            }
            temp = temp*10 + s.charAt(idx+i) - '0';
            if(temp <= 255){
                dfs(s,curr + temp + ".",idx + i,len + 1);
            }
            
        }
    }

Log in to reply
 

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