784. Letter Case Permutation
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.
Examples: Input: S = "a1b2" Output: ["a1b2", "a1B2", "A1b2", "A1B2"] Input: S = "3z4" Output: ["3z4", "3Z4"] Input: S = "12345" Output: ["12345"]
Note:
S
will be a string with length at most12
.S
will consist only of letters or digits.
借鉴的很好的思路,一般这种问题我第一想法是递归,但能用迭代解决是最好不过。
迭代中,当遇到字母时,将已处理好的所有字符串再次取出,并按照其它字母不变、仅当前字母分大小写两种形式再次形成新字符串,对应14-19行代码,这里要删除头结点,用LinkedList会更合理一点,最后存入列表。
1 public class Solution 2 { 3 public IList<string> LetterCasePermutation(string S) 4 { 5 List<string> res = new List<string>(); 6 7 res.Add(S); 8 for (int i = 0; i < S.Length; i++) 9 { 10 if (Char.IsLetter(S[i])) 11 { 12 for (int j = res.Count() - 1; j >= 0; j--) 13 { 14 string str = res[0]; 15 res.RemoveAt(0); 16 string left = str.Substring(0, i); 17 string right = str.Substring(i+1); 18 res.Add(left + char.ToLower(S[i]) + right); 19 res.Add(left + char.ToUpper(S[i]) + right); 20 } 21 } 22 } 23 return res; 24 } 25 }
原文地址:https://www.cnblogs.com/EasonDongH/p/9536484.html
时间: 2024-11-24 03:14:03