LeetCode

Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:

Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

Java

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> sols = new ArrayList<String>();
        if(s == null || s.length() > 12 || s.length() < 4) {
            return sols;
        }
        helper(s, 0, 1, "", sols);
        return sols;
    }

    private void helper(String s, int index, int count, String sol, List<String> sols) {
        if(index >= s.length()) {
            return;
        }

        if(count == 4) {
            String str = s.substring(index);
            if(isValid(str)) {
                sols.add(sol + "." + str);
            }
            return;
        }

        for(int i = 1; i <= 3 && index + i <= s.length(); i++) {
            String str = s.substring(index, index + i);
            if(isValid(str)) {
                if(count == 1) {
                    helper(s, index + i, count + 1, str, sols);
                } else {
                    helper(s, index + i, count + 1, sol + "." + str, sols);
                }
            }
        }
    }

    private boolean isValid(String str) {
        if(str == null || str.length() > 3) {
            return false;
        } 

        if(str.charAt(0) == '0' && str.length() > 1) {
            return false;
        }  

        int num = Integer.parseInt(str);  
        if(num >= 0 && num <= 255) {
            return true;
        }  
        return false;  
    }
}