1 public class Solution 2 { 3 4 public string[] Permute(string S) 5 { 6 List
> dic = new List
>(); 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 ();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 LetterCombinations(string S, string mask, List
> dic)34 {35 var combinations = new List ();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 ();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 }
思路分析:将字符串的"{}"内的部分和常规字符分开处理。对于大括号内的部分,先将括号内的字符进行“组合”,然后再把常规字符插入到相应的位置。
本题的主要思想和是一样的。