Leetcode 784. Letter Case Permutation
Leetcode Problem 784: 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.
s = "a1b2"
["a1b2", "a1B2", "A1b2", "A1B2"]
s
will be a string with length between 1 and 12.s
will consist only of letters and digits.#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> letterCasePermutation(string s) {
vector<string> result;
backtrack(s, 0, "", result);
return result;
}
private:
void backtrack(string &s, int index, string current, vector<string> &result) {
if (index == s.size()) {
result.push_back(current);
return;
}
char c = s[index];
if (isalpha(c)) {
// Choice 1: Keep the current character in lowercase
backtrack(s, index + 1, current + (char)tolower(c), result);
// Choice 2: Change the current character to uppercase
backtrack(s, index + 1, current + (char)toupper(c), result);
} else {
// If the character is not a letter, keep it as is
backtrack(s, index + 1, current + c, result);
}
}
};
s
. This is because each letter can be either in lowercase or uppercase, hence there are (2^N) possible combinations.This solution should be efficient enough given the constraint that (s) can have a maximum length of 12.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?