给定一个字符串S
,通过将字符串S
中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例: 输入: S = "a1b2" 输出: ["a1b2", "a1B2", "A1b2", "A1B2"] 输入: S = "3z4" 输出: ["3z4", "3Z4"] 输入: S = "12345" 输出: ["12345"]
注意:
S
的长度不超过12
。S
仅由数字和字母组成。
这题的做法比较简单的是递归,当遍历遇到数字时,一直遍历下去到字母,遇到字母则分别进入两条路,一条大写,一条小写,直到遍历到末尾,把答案添加到List中。
这里可以注意一下优化遇到数字的逻辑处理,遇到数字的时候不需要参与递归,直接遍历就好了。
代码如下:
1 class Solution { 2 List<String> ans = new LinkedList<>(); 3 4 public List<String> letterCasePermutation(String S) { 5 dfs("", S, 0); 6 return ans; 7 } 8 9 public void dfs(String tmp, String S, int index) { 10 11 if (index == S.length()) 12 ans.add(tmp); 13 else { 14 char ch = S.charAt(index); 15 if (!Character.isLetter(ch)) // 不是字母,是数字 16 { 17 int tmpindex = index; 18 String add = ""; 19 while (!Character.isLetter(S.charAt(tmpindex))) { 20 add += S.charAt(tmpindex); 21 tmpindex++; 22 } 23 dfs(tmp + add, S, tmpindex); 24 } else { 25 26 ch = Character.toLowerCase(ch); 27 dfs(tmp + ch, S, index + 1); 28 ch = Character.toUpperCase(ch); 29 dfs(tmp + ch, S, index + 1); 30 } 31 } 32 } 33 }