题意: 字母变成大小写,数字不变
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); } } }