leetcode/1081: monotonic stack#385
Conversation
There was a problem hiding this comment.
Code Review
This pull request adds a Rust solution for LeetCode problem 1081, "Smallest Subsequence of Distinct Characters", including tests and a README. The reviewer suggested optimizing the solution by working directly with bytes (u8) instead of char to avoid UTF-8 decoding overhead and simplify the logic.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| fn index(x: char) -> usize { | ||
| (x as u8 - b'a') as usize | ||
| } | ||
|
|
||
| impl Solution { | ||
| pub fn smallest_subsequence(s: String) -> String { | ||
| let mut last_index = [None; 26]; | ||
| for (i, c) in s.char_indices() { | ||
| last_index[index(c)] = Some(i); | ||
| } | ||
| let mut used = [false; 26]; | ||
| let mut answer: Vec<char> = vec![]; | ||
| for (i, c) in s.char_indices() { | ||
| let ci = index(c); | ||
| if used[ci] { | ||
| continue; | ||
| } | ||
| while let Some(top) = answer.last().cloned() { | ||
| let ti = index(top); | ||
| if top > c && last_index[ti] > Some(i) { | ||
| answer.pop(); | ||
| used[ti] = false; | ||
| } else { | ||
| break; | ||
| } | ||
| } | ||
| used[ci] = true; | ||
| answer.push(c); | ||
| } | ||
| answer.into_iter().collect() | ||
| } |
There was a problem hiding this comment.
Since the input string s is guaranteed to consist of lowercase English letters (ASCII), we can optimize the implementation by working directly with bytes (u8) instead of char. This avoids the overhead of UTF-8 decoding in char_indices() and simplifies the code by removing the need for Option wrapping in last_index and the helper index function.
impl Solution {
pub fn smallest_subsequence(s: String) -> String {
let bytes = s.as_bytes();
let mut last_index = [0; 26];
for (i, &b) in bytes.iter().enumerate() {
last_index[(b - b'a') as usize] = i;
}
let mut used = [false; 26];
let mut answer: Vec<u8> = vec![];
for (i, &b) in bytes.iter().enumerate() {
let bi = (b - b'a') as usize;
if used[bi] {
continue;
}
while let Some(&top) = answer.last() {
let ti = (top - b'a') as usize;
if top > b && last_index[ti] > i {
answer.pop();
used[ti] = false;
} else {
break;
}
}
used[bi] = true;
answer.push(b);
}
String::from_utf8(answer).unwrap()
}
No description provided.