My C# solution


  • 0
    S
    public class Solution {
        public List<string> RestoreIpAddresses(string s) 
        {
            List<string> result = new List<string>();
            
            for(int i = 1; i<4 && i+3<=s.Length; i++)
            {
                for(int j=1; j<4 && i+j+2<=s.Length; j++)
                {
                    for(int k=1; k<4 && i+j+k+1<=s.Length; k++)
                    {
                        var str1 = s.Substring(0,i);
                        var str2 = s.Substring(i,j);
                        var str3 = s.Substring(i+j,k);
                        var str4 = s.Substring(i+j+k);
                        if(IsValid(str1) && IsValid(str2) && IsValid(str3) && IsValid(str4))
                            result.Add(str1+"."+str2+"."+str3+"."+str4);
                    }
                }
            }
            
            return result;
        }
        
        private bool IsValid(string str)
        {
            if(string.IsNullOrEmpty(str) || str.Length>3 || (str[0]=='0'&&str.Length>1)|| int.Parse(str)>255)
                return false;
            return true;
        }
    
    

Log in to reply
 

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