LeetCode Online Judge 题目C# 练习 - Restore IP Addresses

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)

 1         public static List<string> ResotreIPAddress(string s)

 2         {

 3             if (s.Length < 4 || s.Length > 12)

 4                 return null;

 5 

 6             List<string> ret = new List<string>();

 7 

 8             int n = s.Length - 1;

 9             int i = 0;

10             for (int j = i + 1; j <= n - 2; j++)

11             {

12                 for (int k = j + 1; k <= n - 1; k++)

13                 {

14                     for (int l = k + 1; l <= n; l++)

15                     {

16                         string a = s.Substring(i, j - i), b = s.Substring(j, k - j), c = s.Substring(k, l - k), d = s.Substring(l);

17                         if (RestoreIPAddressIsValid(a, b, c, d))

18                             ret.Add(a + "." + b + "." + c + "." + d);

19                     }

20                 }

21             }

22 

23             return ret;

24         }

25 

26         public static bool RestoreIPAddressIsValid(string a, string b, string c, string d)

27         {

28             // check length for each block

29             if (!(a.Length < 4 && b.Length < 4 && c.Length < 4 && d.Length < 4))

30                 return false;

31             // check if each block length == 1 or NOT begin with 0

32             if (!((a.Length == 1 || a[0] != '0') && (b.Length == 1 || b[0] != '0') && (c.Length == 1 || c[0] != '0') && (d.Length == 1 || d[0] != '0')))

33                 return false;

34 

35             int aVal = int.Parse(a), bVal = int.Parse(b), cVal = int.Parse(c), dVal = int.Parse(d);

36 

37             // check if each block's value is valid

38             if (aVal > 255 || bVal > 255 || cVal > 255 || dVal > 255)

39                 return false;

40 

41             return true;

42         }

代码分析:

  BF,但是可以过LeetCode 的 Online Judge. 不知道有没有更好的方法。 这一题的跟之后的 Sudoku Solver 思路相似,穷举所有答案,然后用一个isValid方法筛选。

你可能感兴趣的:(LeetCode)