LeetCode 93. Restore IP Addresses

Problem:

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)

Solution:

Use recursion. Mind the cases like “010010”, no ip can be “0.10.01.0”.

public class Solution {
    ArrayList<String> result = new ArrayList<String>();
    public List<String> restoreIpAddresses(String s) {
        getIP(s, "", 3);
        return result;
    }
    
    private void getIP(String source, String current, int left) {
        if (left == 0) {
            if (source.length() < 1 || source.length() > 3) return;
            if (source.length() > 1 && source.charAt(0) == '0') return;
            int ip = Integer.parseInt(source);
            if (ip >= 0 && ip <= 255) {
                result.add(current + source);
            }
        }
        else {
            for (int i = 1; i < 4; i++) {
                int end = i < source.length() ? i : source.length();
                if (end == 0) return;
                String cut = source.substring(0, end);
                if (cut.length() > 1 && cut.charAt(0) == '0') return;
                int ip = Integer.parseInt(cut);
                if (ip >= 0 && ip <= 255) {
                    getIP(source.substring(end), current + ip + ".", left - 1);
                }
            }
        }
    }
}