1081. Smallest Subsequence of Distinct Characters

Return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.

Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/

 

Example 1:

Input: s = "bcabc"
Output: "abc"

Example 2:

Input: s = "cbacdcbc"
Output: "acdb"

 

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.

Rust Solution

struct Solution;

impl Solution {
    fn smallest_subsequence(text: String) -> String {
        let mut stack: Vec<u8> = vec![];
        let mut left: Vec<usize> = vec![0; 26];
        for b in text.bytes() {
            left[(b - b'a') as usize] += 1;
        }
        let mut visited: Vec<bool> = vec![false; 26];
        for b in text.bytes() {
            left[(b - b'a') as usize] -= 1;
            if !visited[(b - b'a') as usize] {
                visited[(b - b'a') as usize] = true;
                while let Some(&top) = stack.last() {
                    if top > b && left[(top - b'a') as usize] > 0 {
                        visited[(top - b'a') as usize] = false;
                        stack.pop();
                    } else {
                        break;
                    }
                }
                stack.push(b);
            }
        }

        stack.into_iter().map(|b| b as char).collect()
    }
}

#[test]
fn test() {
    let text = "cdadabcc".to_string();
    let res = "adbc".to_string();
    assert_eq!(Solution::smallest_subsequence(text), res);
    let text = "abcd".to_string();
    let res = "abcd".to_string();
    assert_eq!(Solution::smallest_subsequence(text), res);
    let text = "ecbacba".to_string();
    let res = "eacb".to_string();
    assert_eq!(Solution::smallest_subsequence(text), res);
    let text = "leetcode".to_string();
    let res = "letcod".to_string();
    assert_eq!(Solution::smallest_subsequence(text), res);
}

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