LeetCode.784 Letter Case Permutation

topic:

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 most 12.
  • S will consist only of letters or digits.
analyze:

class Solution {
     public static List<String> letterCasePermutation(String S) {
        //Given a string containing only lowercase letters and numbers, change the lowercase to uppercase, and ask how many combinations are there in total
        //idea: use combinatorial optimization to solve
        List<String> list=new ArrayList<>();
        if(S==null||S.length()==0){
            //return empty ""
            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'){
                        // lowercase letters
                        //update letters
                        chs[i]=(char)(chs[i]-32);
                        helper(list,chs,i+1);
                        //change back
                        chs[i]=(char)(chs[i]+32);
                    }else{
                        //uppercase letter
                        chs[i]=(char)(chs[i]+32);
                        helper(list,chs,i+1);
                        chs[i]=(char)(chs[i]-32);
                    }
                    
                }
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324828763&siteId=291194637