1. 程式人生 > >Letter Case Permutation

Letter Case Permutation

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 between 1 and 12.
  • S will consist only of letters or digits.

思路:經典的backtracking,是字母的時候,變換大小,同時原來的字母的branch也要走一遍;如果是數字直接加入繼續走;

這題不是permuation,所以index從start開始,走過的就不用再走了。

class Solution {
    public List<String> letterCasePermutation(String S) {
        List<String> list = new ArrayList<String>();
        if(S == null) return list;
        letterCasePermuHelper(S, list, "", 0);
        return list;
    }
    
    public void letterCasePermuHelper(String S, List<String> list, String prefix, int start) {
        if(prefix.length() == S.length()){
            list.add(prefix);
            return;
        } else {
            for(int i=start; i<S.length(); i++){
                Character c = S.charAt(start);
                if(Character.isLetter(c)){
                    letterCasePermuHelper(S, list, prefix + Character.toString(c), i+1);
                    letterCasePermuHelper(S, list, prefix + changeUporLower(c), i+1);
                } else {
                    letterCasePermuHelper(S, list, prefix + Character.toString(c), i+1);
                }
            }
        }
    }
    
    public Character changeUporLower(Character c){
        if('a'<=c && c<='z'){
            return Character.toUpperCase(c);
        } else {
            return Character.toLowerCase(c);
        }
    }
}

思路2:用char[] 來做,速度快很多,原因就是減少了java裡面的string contactnation。space變成了N

class Solution {
    public List<String> letterCasePermutation(String S) {
        List<String> list = new ArrayList<String>();
        if(S == null) return list;
        
        letterCasePermuHelper( list, S.toCharArray(), 0);
        return list;
    }
    
    public void letterCasePermuHelper( List<String> list, char[] chars, int index) {
        if(index == chars.length){
            list.add(new String(chars));
            return;
        } else {
            if(Character.isLetter(chars[index])){
                chars[index] = Character.toLowerCase(chars[index]);
                letterCasePermuHelper(list, chars, index+1);
                chars[index] = Character.toUpperCase(chars[index]);
                letterCasePermuHelper(list, chars, index+1);
            }  else {
                letterCasePermuHelper(list, chars, index+1);
            }  
        }
    }
}