Simple 3 nested loops in java


  • 0
    I
    public class Solution {
        public List<String> restoreIpAddresses(String s) {
            
            ArrayList<String> res = new ArrayList<String>();
            for(int i = 0; i < 3 && i + 3 < s.length(); i++) {
                String a = s.substring(0, i + 1);
                if(!valid(a)) continue;
                
                for(int j = i + 1; j < i + 4 && j < s.length(); j++) {
                    String b = s.substring(i + 1, j + 1);
                    if(!valid(b)) continue;
                    
                    for(int k = j + 1; k < j + 4 && k < s.length() && s.length() - k - 1 > 0; k++) {
                        String c = s.substring(j + 1, k + 1);
                        if(!valid(c)) continue;
                        
                        String d = s.substring(k + 1, s.length());
                        if(!valid(d)) continue;
                        
                        res.add(a + "." + b + "." + c + "." + d);
                    }
                }
            }
            
            return res;
        }
        
        private boolean valid(String s) {
            if(s.charAt(0) == '0' && s.length() > 1) {
                return false;
            }
            
            if(s.length() > 3) {
                return false;
            }
            return Integer.parseInt(s) < 256;
        }
    }
    

Log in to reply
 

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