题目:
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.
class Solution { public static List<String> letterCasePermutation(String S) { //给定只包含小写字母和数字的字符串,将其中的小写换成大写,问一共有多少中组合 //思路:使用组合优化求解 List<String> list=new ArrayList<>(); if(S==null||S.length()==0){ //返回空“” list.add(""); return list; } char [] chs=S.toCharArray(); helper(list,chs,0); return list; } public static void helper(List<String> list,char [] chs,int index){ list.add(String.valueOf(chs)); if(index==chs.length){ return ; }else{ for(int i=index;i<chs.length;i++){ if(!Character.isDigit(chs[i])){ if(chs[i]>='a'&&chs[i]<='z'){ //为小写字母 //更新字母 chs[i]=(char)(chs[i]-32); helper(list,chs,i+1); //更改回来 chs[i]=(char)(chs[i]+32); }else{ //大写字母 chs[i]=(char)(chs[i]+32); helper(list,chs,i+1); chs[i]=(char)(chs[i]-32); } } } } } }