leetcode 784. Letter Case Permutation——所有BFS和DFS的题目本质上都可以抽象为tree,这样方便你写代码
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
标签:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-03-14 cassandra cpp driver中bind list——用cass_statement_bind_collection函数
2017-03-14 parquet文件格式——本质上是将多个rows作为一个chunk,同一个chunk里每一个单独的column使用列存储格式,这样获取某一row数据时候不需要跨机器获取
2017-03-14 WebAssembly,可以作为任何编程语言的编译目标,使应用程序可以运行在浏览器或其它代理中——浏览器里运行其他语言的程序?