My java solution, very easy to understand


  • 1
    H
    public List<String> restoreIpAddresses(String s) {
        List<String> output = new ArrayList<String>();
    	if(s.length() > 0) {helper(output, s, "", 4);}
    	return output;
    }
    private void helper(List<String> output, String s, String ipAddress, int n) {
    	if (n == 1) {
    		if (s.length() == 1 ||
    			(s.length() == 2 && Integer.parseInt(s.substring(0, 2)) > 9) ||
    			(s.length() == 3 && Integer.parseInt(s) > 99 && Integer.parseInt(s) < 256)) {
    		    ipAddress += s;
    		    output.add(ipAddress);
    		}
    		return;
    	}
    	if (s.length() > 1)
    		helper(output, s.substring(1), ipAddress + s.substring(0, 1) + ".", n - 1);   	    
    	if (s.length() > 2 && Integer.parseInt(s.substring(0, 2)) > 9)
    		helper(output, s.substring(2), ipAddress + s.substring(0, 2) + ".", n - 1);
    	if (s.length() > 3 && Integer.parseInt(s.substring(0, 3)) > 99 && Integer.parseInt(s.substring(0, 3)) < 256)
    		helper(output, s.substring(3), ipAddress + s.substring(0, 3) + ".", n - 1);
    }

Log in to reply
 

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