加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

leetcode1087

发布时间:2020-12-14 04:44:01 所属栏目:大数据 来源:网络整理
导读:1 public class Solution 2 { 3 4 public string [] Permute( string S) 5 { 6 ListList char dic = new ListList char (); 7 int baseindex = 0 ; 8 var temp = S; 9 var mask = "" ; 10 while (temp.IndexOf( ‘ { ‘ ) = 0 ) 11 { 12 int begin = temp.In
 1 public class Solution
 2     {
 3 
 4         public string[] Permute(string S)
 5         {
 6             List<List<char>> dic = new List<List<char>>();
 7             int baseindex = 0;
 8             var temp = S;
 9             var mask = "";
10             while (temp.IndexOf({) >= 0)
11             {
12                 int begin = temp.IndexOf({);
13                 int end = temp.IndexOf(});
14                 var ary = new List<char>();
15                 for (int i = begin + 1; i < end; i++)
16                 {
17                     if (temp[i] != ,)
18                     {
19                         ary.Add(temp[i]);
20                     }
21                 }
22                 dic.Add(ary);
23                 mask = mask + temp.Substring(0,begin) + "#";
24                 baseindex = end + 1;
25                 temp = temp.Substring(baseindex);
26             }
27             mask += S.Substring(S.LastIndexOf(}) + 1);
28 
29             var result = LetterCombinations(S,mask,dic);
30             return result.OrderBy(x => x).ToArray();
31         }
32 
33         public IList<string> LetterCombinations(string S,string mask,List<List<char>> dic)
34         {
35             var combinations = new List<string>();
36 
37             if (string.IsNullOrEmpty(S))
38                 return combinations;
39 
40             combinations.Add("");
41             foreach (var digits in dic)
42             {
43                 var next = new List<string>();
44 
45                 foreach (char letter in digits)
46                 {
47                     foreach (string combo in combinations)
48                     {
49                         var dstr = combo + letter;
50                         next.Add(dstr);
51                     }
52                 }
53                 combinations = next;
54             }
55 
56             for (int i = 0; i < combinations.Count; i++)
57             {
58                 var cur = combinations[i];
59                 for (var j = 0; j < mask.Length; j++)
60                 {
61                     if (mask[j] != #)
62                     {
63                         cur = cur.Insert(j,mask[j].ToString());
64                     }
65                 }
66                 combinations[i] = cur;
67             }
68 
69             return combinations;
70         }
71     }

?

思路分析:将字符串的"{}"内的部分和常规字符分开处理。对于大括号内的部分,先将括号内的字符进行“组合”,然后再把常规字符插入到相应的位置。

本题的主要思想和leetcode17: Letter Combinations of a Phone Number是一样的。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读