My Java Code, Simple and Short


  • 0
    J
    public class Solution {
        List<String> res = new ArrayList<> ();
        public List<String> restoreIpAddresses(String s) {
            backtrack(s,0,"",4);
            return res;
        }
        public void backtrack(String s, int index, String cur,int left){
            if(index==s.length()&&left==0){
                res.add(cur);return;
            }
            
            if(!cur.equals("")) cur = cur+".";
            
            for(int i=index+1;i<=index+3&&i<=s.length();i++){
                if(i>index+1&&s.charAt(index)=='0') break;
                String sub = s.substring(index,i);
                int value = Integer.parseInt(sub);
                if(value>=0&&value<=255&&left>0){
                    backtrack(s,i,cur+sub,left-1);
                }
            }
        }
    }
    

Log in to reply
 

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