My code in C#


  • 0
    F

    public class Solution {
    public IList<string> RestoreIpAddresses(string s) {
    IList<string> ips = new List<string>();

        if(s.Length < 4 || s.Length > 12) return ips;
        
        
        for(int i = 1; i <= 3; i++)
        for(int j = 1; j <= 3; j++)
        for(int k = 1; k <= 3; k++)
        {
            int l = s.Length - i - j - k;
            if(l <= 0 || l > 3) continue;
            
            StringBuilder ip = new StringBuilder();
            if(AppendSection(s.Substring(0, i),ip, true)
            && AppendSection(s.Substring(i, j),ip)
            && AppendSection(s.Substring(i+j,k),ip)
            && AppendSection(s.Substring(i + j + k, l),ip)
            )
            {
                ips.Add(ip.ToString());
            }           
        }        
        return ips;
    }
    
    bool AppendSection(string section, StringBuilder ip, bool first = false)
    {
        if(section.Length > 1 && section[0] == '0')
        {
            return false;
        }
        int value = int.Parse(section);
         if(value >= 0 && value <=255)
        {
            if(!first)
            {
            ip.Append(".");
            }
            ip.Append(value.ToString());
            return true;
        }        
        return false;
    }
    

    }


Log in to reply
 

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