LeetCode-93.Restore IP Addresses

来源:互联网 发布:高考摄影专业知乎 编辑:程序博客网 时间:2024/05/16 05:37

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

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

public class Solution {    public IList<string> RestoreIpAddresses(string s)    {        IList<string> list = new List<string>();        Fun(list, "",0, s);        return list;    }    private void Fun(IList<string> list,string item, int dot, string s)    {         if (s.Length > (4 - dot) * 3)            return;                    if (dot==3 && IsValid(s))        {            item += s;            list.Add(item);            return;        }        for (int i = 1; i <= 3; i++)        {            if (s.Length>i)            {                string temp = s.Substring(0, i);                if (IsValid(temp))                {                    Fun(list, item + temp + ".", dot + 1, s.Substring(i));                }             }        }    }    private bool IsValid(string v)    {        if (v.StartsWith("0")&&v.Length>1)            return false;        int n = Convert.ToInt16(v);        return 0 <= n && n <= 255;    }}

public class Solution {    public IList<string> RestoreIpAddresses(string s)    {        IList<string> list = new List<string>();        int len = s.Length;        for (int i = 1; i < 4; i++)        {            for (int j = 1; j < 4; j++)            {                for (int k = 1; k < 4; k++)                {                    if (i + j + k + 3 >= len&& i + j + k < len)                    {                        string s1 = s.Substring(0, i), s2 = s.Substring(i, j), s3 = s.Substring(i + j, k), s4 = s.Substring(i + j + k);                        if (IsValid(s1) && IsValid(s2) && IsValid(s3) && IsValid(s4))                        {                            list.Add(s1 + "." + s2 + "." + s3 + "." + s4);                        }                    }                }            }        }        return list;    }        private bool IsValid(string v)    {        if (v.StartsWith("0") && v.Length > 1)            return false;        int n = Convert.ToInt16(v);        return 0 <= n && n <= 255;    }}


0 0
原创粉丝点击