Java Easy Understand Solution


  • 1
    H

    '''
    public class Solution {

    List<String> res;
    
    public List<String> restoreIpAddresses(String s) {
        res = new ArrayList<>();
        if (s.length() == 0) return res;
        
        backTracking(s, "", 4);
        
        return res;
    }
    
    private void backTracking(String s, String element, int count) {
        if (s.length() == 0 && count == 0) {
            res.add(element.substring(0, element.length()-1));
            return;
        }
        if (s.length() == 0 || count == 0) return;
        
        for (int i = 1; i <= s.length(); i ++) {
            String sub = s.substring(0, i);
            if (isValid(sub)) {
                backTracking(s.substring(i), element + sub + ".", count - 1);
            } else break;
        }
    }
    
    private boolean isValid(String s) {
        int val = Integer.valueOf(s);
        if (val > 255) return false;
        return s.length() == String.valueOf(val).length();
    }
    

    }
    '''


  • 0
    M
    private boolean isValid(String s) {
        int val = Integer.valueOf(s);
        if (val > 255) return false;
        return s.length() == String.valueOf(val).length();
    }
    

    I learnt this from you today. I was wondering how to check for the difference between '01' and '1'. Thanks for sharing your solution.


Log in to reply
 

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