#3758
Medium Algorithms Convert number words to digits
String Trie
70.3% acceptance
Mar 31, 2026
4
1
You are given a string s consisting of lowercase English letters. s may contain valid concatenated English words representing the digits 0 to 9, without spaces.
Your task is to extract each valid number word in order and convert it to its corresponding digit, producing a string of digits.
Parse s from left to right. At each position:
If a valid number word starts at the current position, append its corresponding digit to the result and advance by the length of that word.
Otherwise, skip exactly one character and continue parsing.
Return the resulting digit string. If no number words are found, return an empty string.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn convert_number(s: String) -> String {
let words = [
("zero", '0'), ("one", '1'), ("two", '2'), ("three", '3'),
("four", '4'), ("five", '5'), ("six", '6'), ("seven", '7'),
("eight", '8'), ("nine", '9'),
];
let b = s.as_bytes();
let n = b.len();
let mut result = String::new();
let mut i = 0;
while i < n {
let mut found = false;
for &(word, digit) in &words {
let wb = word.as_bytes();
if i + wb.len() <= n && &b[i..i + wb.len()] == wb {
result.push(digit);
i += wb.len();
found = true;
break;
}
}
if !found {
i += 1;
}
}
result
}
}