文章目录
- 1 题目理解
- 2 回溯
1 题目理解
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. You can return the output in any order.
输入:字符串
输出:字符串可能的变形
规则:每一个位置上的字符都可能变为大写或者小写。非字母的保持原字母。
Example 1:
Input: S = “a1b2”
Output: [“a1b2”,“a1B2”,“A1b2”,“A1B2”]
2 回溯
每个字符位,可能是大写,也可能是小写。回溯递归即可实现。
class Solution {private String S;private List<String> answer;public List<String> letterCasePermutation(String S) {this.S = S;answer = new ArrayList<String>();dfs(0,"");return answer;}private void dfs(int index,String str){if(index >= S.length()){answer.add(str);}else{char ch = S.charAt(index);if(ch>='0' && ch<='9'){dfs(index+1,str+ch);}else if(ch>='A' && ch<='Z'){dfs(index+1,str+ch);ch += 32;dfs(index+1,str+ch);}else if(ch>='a' && ch<='z'){dfs(index+1,str+ch);ch -= 32;dfs(index+1,str+ch);}}}
}
第二种方式:可以使用二进制位。对于每一位有两种选择的情况可以用二进制位来解决。
class Solution {public List<String> letterCasePermutation(String S) {int charCount = 0;for(char ch : S.toCharArray()){if(Character.isLetter(ch)){charCount++;}}List<String> answer = new ArrayList<String>();int max = (1<<charCount)-1;for(int i = 0;i<=max;i++){int j = 0;StringBuilder s = new StringBuilder();for(char ch : S.toCharArray()){if(Character.isLetter(ch)){if(((i>>j) &1)==1){s.append(Character.toLowerCase(ch));}else{s.append(Character.toUpperCase(ch));}j++;}else{s.append(ch);}}answer.add(s.toString());}return answer;}
}
此处用StringBuilder比String快了不好。