Skip to content

Latest commit

 

History

History
159 lines (126 loc) · 3.34 KB

File metadata and controls

159 lines (126 loc) · 3.34 KB

中文文档

Description

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. You can return the output in any order.

 

Example 1:

Input: S = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]

Example 2:

Input: S = "3z4"
Output: ["3z4","3Z4"]

Example 3:

Input: S = "12345"
Output: ["12345"]

Example 4:

Input: S = "0"
Output: ["0"]

 

Constraints:

  • S will be a string with length between 1 and 12.
  • S will consist only of letters or digits.

Solutions

DFS.

Python3

class Solution:
    def letterCasePermutation(self, s: str) -> List[str]:
        def dfs(i, t):
            if i == len(t):
                ans.append(''.join(t))
                return
            dfs(i + 1, t)
            if t[i].isalpha():
                t[i] = t[i].upper() if t[i].islower() else t[i].lower()
                dfs(i + 1, t)

        ans = []
        t = list(s)
        dfs(0, t)
        return ans
class Solution:
    def letterCasePermutation(self, s: str) -> List[str]:
        def dfs(i, t):
            if i == len(s):
                ans.append(t)
                return
            if s[i].isalpha():
                dfs(i + 1, t + s[i].upper())
                dfs(i + 1, t + s[i].lower())
            else:
                dfs(i + 1, t + s[i])

        ans = []
        dfs(0, '')
        return ans

Java

class Solution {
    public List<String> letterCasePermutation(String S) {
        char[] cs = S.toCharArray();
        List<String> res = new ArrayList<>();
        dfs(cs, 0, res);
        return res;
    }

    private void dfs(char[] cs, int i, List<String> res) {
        if (i == cs.length) {
            res.add(String.valueOf(cs));
            return;
        }
        dfs(cs, i + 1, res);
        if (cs[i] >= 'A') {
            cs[i] ^= 32;
            dfs(cs, i + 1, res);
        }
    }
}

C++

class Solution {
public:
    vector<string> ans;
    string s;

    vector<string> letterCasePermutation(string s) {
        this->s = s;
        string t = "";
        dfs(0, t);
        return ans;
    }

    void dfs(int i, string t) {
        if (i == s.size())
        {
            ans.push_back(t);
            return;
        }
        if (isalpha(s[i]))
        {
            char c1 = toupper(s[i]);
            char c2 = tolower(s[i]);
            dfs(i + 1, t + c1);
            dfs(i + 1, t + c2);
        }
        else
        {
            dfs(i + 1, t + s[i]);
        }
    }
};

...