Restore IP Addresses


#1

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

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

#2

The below code uses 4 loops to control all the 4 tokens of an IP address.

func restoreIpAddresses(s string) []string {
    result := make([]string, 0)
    slen := len(s)
    for i:=1;i<4 && i<slen-2;i++{
        for j:=i+1;j<i+4 && j<slen-1;j++{
            for k:=j+1;k<j+4 && k<slen;k++{
                s1:=s[0:i]
                s2:=s[i:j]
                s3:=s[j:k]
                s4:=s[k:slen]
                if (isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4)){
                    result = append(result, s1+"."+s2+"."+s3+"."+s4)
                }
            }
        }
    }
    
    return result
}

func isValid(s string)bool{
    si, _ := strconv.Atoi(s)
    if (len(s)>3 || len(s)==0 || (s[0]=='0' && len(s)>1) || si>255){
        return false
    }
    return true
}