# 784.Letter-Case-Permutation

## 784. Letter Case Permutation

## 题目地址

<https://leetcode.com/problems/letter-case-permutation/>

## 题目描述

```
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 between 1 and 12.
S will consist only of letters or digits.
```

## 代码

### Approach #1 Recursion

```java
class Solution {
  public List<String> letterCasePermutation(String S) {
        List<StringBuilder> ans = new ArrayList();
    ans.add(new StringBuilder());

    for (char c: S.toCharArray()) {
      int n = ans.size();
      if (Character.isLetter(c)) {
        for (int i = 0; i < n; i++) {
          ans.add(new StringBuilder(ans.get(i)));
          ans.get(i).append(Character.toLowerCase(c));
          ans.get(n + i).append(Character.toUpperCase(c));
        }
      } else {
        for (int i = 0; i < n; i++) {
          ans.get(i).append(c);
        }
      }
    }
    List<String> finalans = new ArrayList();
    for (StringBuilder sb: ans) {
      finalans.add(sb.toString());
    }
    return finalans;
  }
}
```

### Approach #2 Binary Mask

```java
class Solution {
  public List<String> letterCasePermutation(String S) {
    int count = 0;
    for (char c: S.toString()) {
      if (Character.isLetter(c)) {
        count++;
      }
    }

    List<String> ans = new ArrayList();

    for (int bits = 0; bits < 1 << count; bits++) {
      int b = 0;
      StringBuilder word = new StringBuilder();
      for (char letter: S.toCharArray()) {
        if (Character.isLetter(letter)) {
          if (((bits >> b++) & 1 == 1) {
            word.append(Character.toLowerCase(letter));
          } else {
            word.append(Character.toUpperCase(letter));
          }
        } else {
          word.append(letter);
        }
      }
    }

    return ans;
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/string/784.letter-case-permutation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
