1. 程式人生 > >784. Letter Case Permutation---back tracking

784. Letter Case Permutation---back tracking

題意: 字母變成大小寫,數字不變
Examples: Input: S = "a1b2" Output: ["a1b2", "a1B2", "A1b2", "A1B2"] Input: S = "3z4" Output: ["3z4", "3Z4"] Input: S = "12345" Output: ["12345"]


S = a1bc, 畫出遞迴數如下:如果是字母 就是一個二叉樹, 如果是數字就一個節點。所以本質上是一個二叉樹的back tracking.

因為不熟悉 Java 字串處理的一些function, 一開始寫了一個特別醜陋的code:

class Solution {
    
public List<String> letterCasePermutation(String S) { List<String> result = new ArrayList<>(); StringBuilder sb = new StringBuilder(S); dfs(new StringBuilder(), sb, result,0); return result; } private void dfs(StringBuilder curResult, StringBuilder S, List<String> result, int
index){ if(curResult.length() == S.length()){ result.add(curResult.toString()); return; } char c = S.charAt(index); curResult.append(c); dfs(curResult,S,result,index+1); curResult.setLength(curResult.length()
-1); if(c>='a' && c<='z'){ char ch = change_char(c, true); S.setCharAt(index,ch); curResult.append(ch); dfs(curResult,S,result,index+1); curResult.setLength(curResult.length()-1); S.setCharAt(index,c); } else if(c>='A' && c<='Z'){ char ch = change_char(c,false); S.setCharAt(index,ch); curResult.append(ch); dfs(curResult,S,result,index+1); curResult.setLength(curResult.length()-1); S.setCharAt(index,c); } } private char change_char(char c, boolean small){ if(small){ return (char)(c + 'A'-'a'); } else return (char)(c + 'a'-'A'); } }

用了Character 類裡的function 後的code:

優化到了95%

class Solution {
    public List<String> letterCasePermutation(String S) {
        
        List<String> result = new ArrayList<>();
        dfs(new StringBuilder(), S, result,0);
        return result;
    
    }
    
    private void dfs(StringBuilder curResult, String S, List<String> result, int index){
        
          if(curResult.length() == S.length()){
              result.add(curResult.toString());
              return;
          }
           
          Character c = S.charAt(index); 
        
          if(Character.isLetter(c)){
              // left sub tree
              curResult.append(Character.toLowerCase(c));
              dfs(curResult,S,result,index+1);
              curResult.deleteCharAt(curResult.length()-1);
              
              //right sub tree
              curResult.append(Character.toUpperCase(c));
              dfs(curResult,S,result,index+1);
              curResult.deleteCharAt(curResult.length()-1);  
          }
        
          else{ // is number
              curResult.append(c);
              dfs(curResult,S,result,index+1);
              curResult.deleteCharAt(curResult.length()-1);
          }    
    }
}