题目
给定一个字符串 s ,通过将字符串 s 中的每个字母转变大小写,我们可以获得一个新的字符串。
返回 所有可能得到的字符串集合 。以 任意顺序 返回输出。
示例 1:
输入:s = “a1b2”
输出:[“a1b2”, “a1B2”, “A1b2”, “A1B2”]
示例 2:
输入: s = “3z4”
输出: [“3z4”,”3Z4”]
提示:
- 1 <= s.length <= 12
- s 由小写英文字母、大写英文字母和数字组成
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-case-permutation
题解
从题目中可以观察到,出现一个大小写字母的字符就会出现两个版本,n个字符就会有2的n次幂个版本。
递归图解:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution {
private List<String> res = new ArrayList();
public List<String> letterCasePermutation(String s) { handleRecursive(new StringBuilder(s),0); return res; }
public void handleRecursive(StringBuilder strBuffer,int curIndex){ if(curIndex>=strBuffer.length()){ res.add(strBuffer.toString()); return; }else { char ch = strBuffer.charAt(curIndex); if(ch>='0' && ch<='9'){ handleRecursive(strBuffer,curIndex+1); }else{ handleRecursive(strBuffer,curIndex+1); if(ch>='a' && ch<='z'){ strBuffer.setCharAt(curIndex,(char)(ch-32)); }else if(ch>='A' && ch<='Z'){ strBuffer.setCharAt(curIndex,(char)(ch+32)); } handleRecursive(strBuffer,curIndex+1); } } }
}
|