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 most 12.
  • 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

 

 

 

posted @   bonelee  阅读(416)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.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,可以作为任何编程语言的编译目标,使应用程序可以运行在浏览器或其它代理中——浏览器里运行其他语言的程序?
点击右上角即可分享
微信分享提示