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. 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.

Rust Solution

struct Solution;

impl Solution {
    fn permutation(s: &[char], n: usize, i: usize, t: &mut String, res: &mut Vec<String>) {
        if i == n {
            res.push(t.clone());
        } else {
            if s[i].is_alphabetic() {
                let lower: char = s[i].to_ascii_lowercase();
                let upper: char = s[i].to_ascii_uppercase();
                t.push(lower);
                Self::permutation(s, n, i + 1, t, res);
                t.pop();
                t.push(upper);
                Self::permutation(s, n, i + 1, t, res);
                t.pop();
            } else {
                t.push(s[i]);
                Self::permutation(s, n, i + 1, t, res);
                t.pop();
            }
        }
    }
    fn letter_case_permutation(s: String) -> Vec<String> {
        let n = s.len();
        let s: Vec<char> = s.chars().collect();
        let mut res: Vec<String> = vec![];
        let mut t: String = "".to_string();
        Self::permutation(&s, n, 0, &mut t, &mut res);
        res
    }
}

#[test]
fn test() {
    let s: String = "a1b2".to_string();
    let res: Vec<String> = vec_string!["a1b2", "a1B2", "A1b2", "A1B2"];
    assert_eq!(Solution::letter_case_permutation(s), res);
}

Having problems with this solution? Click here to submit an issue on github.