1096. Brace Expansion II

Under a grammar given below, strings can represent a set of lowercase words.  Let's use R(expr) to denote the set of words the expression represents.

Grammar can best be understood through simple examples:

  • Single letters represent a singleton set containing that word.
    • R("a") = {"a"}
    • R("w") = {"w"}
  • When we take a comma delimited list of 2 or more expressions, we take the union of possibilities.
    • R("{a,b,c}") = {"a","b","c"}
    • R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once)
  • When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.
    • R("{a,b}{c,d}") = {"ac","ad","bc","bd"}
    • R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}

Formally, the 3 rules for our grammar:

  • For every lowercase letter x, we have R(x) = {x}
  • For expressions e_1, e_2, ... , e_k with k >= 2, we have R({e_1,e_2,...}) = R(e_1) ∪ R(e_2) ∪ ...
  • For expressions e_1 and e_2, we have R(e_1 + e_2) = {a + b for (a, b) in R(e_1) × R(e_2)}, where + denotes concatenation, and × denotes the cartesian product.

Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.

 

Example 1:

Input: "{a,b}{c,{d,e}}"
Output: ["ac","ad","ae","bc","bd","be"]

Example 2:

Input: "{{a,z},a{b,c},{ab,z}}"
Output: ["a","ab","ac","z"]
Explanation: Each distinct word is written only once in the final answer.

 

Constraints:

  1. 1 <= expression.length <= 60
  2. expression[i] consists of '{', '}', ','or lowercase English letters.
  3. The given expression represents a set of words based on the grammar given in the description.

Rust Solution

struct Solution;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::iter::Peekable;
use std::str::Chars;
use std::vec::IntoIter;

#[derive(Debug)]
enum Tok {
    S(String),
    Op(char),
}

impl Solution {
    fn brace_expansion_ii(expression: String) -> Vec<String> {
        let mut it = expression.chars().peekable();
        let toks = Self::parse_tokens(&mut it);
        let mut it = toks.into_iter().peekable();
        let mut sorted: Vec<String> = Self::parse(&mut it).into_iter().collect();
        sorted.sort_unstable();
        sorted
    }

    fn concat(a: &HashSet<String>, b: &HashSet<String>) -> HashSet<String> {
        let mut res = HashSet::new();
        for i in a {
            for j in b {
                res.insert(format!("{}{}", i, j));
            }
        }
        res
    }

    fn parse(it: &mut Peekable<IntoIter<Tok>>) -> HashSet<String> {
        let mut res = HashSet::from_iter(vec!["".to_string()]);
        while it.len() != 0 {
            if Self::eat(it, '{') {
                res = Self::concat(&res, &Self::parse(it));
                Self::eat(it, '}');
                continue;
            }
            if Self::eat(it, ',') {
                res = &res | &Self::parse(it);
                continue;
            }
            if let Some(Tok::Op('}')) = it.peek() {
                break;
            }
            if let Some(Tok::S(s)) = it.next() {
                res = Self::concat(&res, &HashSet::from_iter(vec![s]));
                continue;
            }
        }
        res
    }

    fn eat(it: &mut Peekable<IntoIter<Tok>>, c: char) -> bool {
        if let Some(&Tok::Op(t)) = it.peek() {
            if t == c {
                it.next();
                true
            } else {
                false
            }
        } else {
            false
        }
    }

    fn parse_tokens(it: &mut Peekable<Chars>) -> Vec<Tok> {
        let mut res = vec![];
        while let Some(c) = it.next() {
            match c {
                '{' | '}' | ',' => res.push(Tok::Op(c)),
                'a'..='z' => {
                    let mut s = "".to_string();
                    s.push(c);
                    while let Some('a'..='z') = it.peek() {
                        s.push(it.next().unwrap());
                    }
                    res.push(Tok::S(s));
                }
                _ => {}
            }
        }
        res
    }
}

#[test]
fn test() {
    let expression = "{a,b}{c,{d,e}}".to_string();
    let res = vec_string!["ac", "ad", "ae", "bc", "bd", "be"];
    assert_eq!(Solution::brace_expansion_ii(expression), res);
    let expression = "{{a,z},a{b,c},{ab,z}}".to_string();
    let res = vec_string!["a", "ab", "ac", "z"];
    assert_eq!(Solution::brace_expansion_ii(expression), res);
}

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