JAVA concise recursion solution


  • 0
    F
    public class Solution {
        private List<String> result = new ArrayList<String>();
        public List<String> restoreIpAddresses(String s) {
            StringBuilder sb = new StringBuilder();
            helper(s,sb,s.length(),4);
            return result;
        }
        
        public void helper(String s, StringBuilder sb, int len, int count){
            if(count == 0 && sb.length() == len+3){
                result.add(sb.toString());         
                return;
            }
            
            if(s.length() > count*3 || s.length() < count)
                return;
                
            for(int i = 1; i <=3; i++){
                if(s.length() >= i){
                    int cur = Integer.parseInt(s.substring(0,i));
                    if(cur <= 255){
                        if(count > 1)
                            helper(s.substring(i,s.length()), new StringBuilder(sb).append(cur).append("."), len, count-1);
                        else if(count == 1)
                            helper(s.substring(i,s.length()), new StringBuilder(sb).append(cur), len, count-1);
                    }
                }
            }  
        }
    }

  • 0
    A

    Can you explain how your code handle the invalid ip address like "1.11.00.1"?


  • 0
    F

    because Integer.parseInt() will change "00" to "0". Then "if(count == 0 && sb.length() == len+3)" this condition won't be true, because the sb.length() = len+2, not len+3


  • 0
    A

    Got it! Thanks!


  • 0
    K

    Why is 1.11.00.1 invalid by the way?


Log in to reply
 

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