My C# solution


  • 0
    J
    public class Solution {
        List<string> result = new List<string>();
        public IList<string> RestoreIpAddresses(string s) {
            if(s.Length <4 || s.Length > 12) return result;
            //var nums = ParseString(s);
            
            var ip = new string[4];
            var uba = Math.Min(3,s.Length-3);
            for(int a = 1; a <= uba ; a++)
            {
                ip[0] = s.Substring(0,a);
                var ubb = Math.Min(3, s.Length -2 -a);
                for(int b = 1; b <= ubb; b++)
                {
                    ip[1] = s.Substring(a,b);
                    
                    var ubc = Math.Min(3,s.Length -1 -a -b);
                    for(int c = 1; c<= ubc; c++)
                    {
                        ip[2] = s.Substring(a+b, c);
                        ip[3] = s.Substring(a+b+c);
                        AddIfValid(ip);
                    }
                }
            }
            
            return result;
        }
        
        void AddIfValid(string[] ip)
        {
            for(int i = 0; i <4; i++)
            {
                if(ip[i].Length > 1 && ip[i][0] == '0')
                 {
                     return ;
                 }
                 
                var num = 0;
                int.TryParse(ip[i], out num);
                if(num > 255)
                {
                    return;
                }
            }
            
         var ips = string.Format("{0}.{1}.{2}.{3}", ip[0], ip[1], ip[2],ip[3]);
         result.Add(ips);
        }
    }
    

Log in to reply
 

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