前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Letter Case Permutation

Letter Case Permutation

作者头像
用户1147447
发布2019-05-26 00:41:03
4800
发布2019-05-26 00:41:03
举报
文章被收录于专栏:机器学习入门

LWC 72: 784. Letter Case Permutation

传送门:784. Letter Case Permutation

Problem:

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即可,遇到数字跳过,遇到字母,分为两种情况传给子问题。

Java版本:

代码语言:javascript
复制
    public List<String> letterCasePermutation(String S) {
        all = new ArrayList<>();
        backtrack(S.toCharArray(), 0, "");
        return all;
    }

    List<String> all;
    public void backtrack(char[] cs, int pos, String ans) {
        if (pos == cs.length) {
            all.add(ans);
            return;
        }
        else {
            if (Character.isAlphabetic(cs[pos])) {
                char l = cs[pos];
                backtrack(cs, pos + 1, ans + l);
                if (l >= 'a' && l <= 'z') l = (char) (l - 'a' + 'A');
                else if (l >= 'A' && l <= 'Z') l = (char) (l - 'A' + 'a');
                backtrack(cs, pos + 1, ans + l);
            }
            else {
                backtrack(cs, pos + 1, ans + cs[pos]);
            }
        }
    }

Python版本:

代码语言:javascript
复制
class Solution(object):
    def letterCasePermutation(self, S):
        """
        :type S: str
        :rtype: List[str]
        """
        ans = []

        def dfs(S, pos, str):
            if pos == len(S):
                ans.append(str)
                return
            else:
                if S[pos].isalpha():
                    letter = S[pos]
                    dfs(S, pos + 1, str + letter.upper())
                    dfs(S, pos + 1, str + letter.lower())
                else:
                    dfs(S, pos + 1, str + S[pos])
        dfs(S, 0, '')
        return ans
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年02月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 72: 784. Letter Case Permutation
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档