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.
本质上是排列问题,经典的dfs求解。将字符串看作一棵树,dfs遍历过程中修改node为大写或者小写字母即可!
解法1:
class Solution { public: vector<string> letterCasePermutation(string S) { // A! use DFS vector<string> ans; dfs(ans, S, 0); return ans; } void dfs(vector<string> &ans, string &S, int i) { if(i==S.size()) { ans.push_back(string(S)); return; } dfs(ans, S, i+1); #本质上就是等价于tree node的dfs(root.left) if(S[i]>='a' && S[i]<='z') { #本质上就是等价于tree node的dfs(root.right) 如果有right的话 S[i]-=32; dfs(ans, S, i+1); } else if (S[i]>='A' && S[i]<='Z') { S[i]+=32; dfs(ans, S, i+1); } } };
比我精简的写法:
class Solution { void backtrack(string &s, int i, vector<string> &res) { if (i == s.size()) { res.push_back(s); return; } backtrack(s, i + 1, res); if (isalpha(s[i])) { // toggle case s[i] ^= (1 << 5); backtrack(s, i + 1, res); } } public: vector<string> letterCasePermutation(string S) { vector<string> res; backtrack(S, 0, res); return res; } };
使用BFS:本质上和tree的BFS一样,只是tree的node是字符串的char。
class Solution(object): def letterCasePermutation(self, S): """ :type S: str :rtype: List[str] """ # A! problem, use BFS q = [S] # tree的层序遍历也一样 for i in range(0, len(S)): if S[i].isalpha(): q += [s[:i] + chr(ord(s[i]) ^ 32) + s[i+1:] for s in q] return q
另外一种写法:
def letterCasePermutation(self, S): res = [''] for ch in S: if ch.isalpha(): res = [i+j for i in res for j in [ch.upper(), ch.lower()]] else: res = [i+ch for i in res] return res