Convert Number Words to Digits Problem
Description
LeetCode Problem 3758.
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.
Example 1:
Input: s = "onefourthree"
Output: "143"
Explanation:
- Parsing from left to right, extract the valid number words "one", "four", "three".
- These map to digits 1, 4, 3. Thus, the final result is "143".
Example 2:
Input: s = "ninexsix"
Output: "96"
Explanation:
- The substring "nine" is a valid number word and maps to 9.
- The character "x" does not match any valid number word prefix and is skipped.
- Then, the substring "six" is a valid number word and maps to 6, so the final result is "96".
Example 3:
Input: s = "zeero"
Output: ""
Explanation:
- No substring forms a valid number word during left-to-right parsing.
- All characters are skipped and incomplete fragments are ignored, so the result is an empty string.
Example 4:
Input: s = "tw"
Output: ""
Explanation:
- No substring forms a valid number word during left-to-right parsing.
- All characters are skipped and incomplete fragments are ignored, so the result is an empty string.
Constraints:
1 <= s.length <= 10^5scontains only lowercase English letters.
Solution
Approach: Left-to-Right Matching
Keep the ten words zero to nine in an array, so the word at index j stands for digit j. Walk through s with a position i. At each position, try the ten words in turn and check whether s continues with that word. If one matches, append its digit and move i forward by the length of the word. If none matches, skip exactly one character.
No word is a prefix of another (for example one and nine start differently, and eight and three do too), so at most one word can match at a position and the order of the checks does not matter. Words that overlap, such as the one hidden in twone, behave as the statement says: the first match consumes its letters.
Join the collected digits and return the string.
Complexity: O(10n) time, which is O(n), and O(1) extra space besides the output.
class Solution:
def convertNumber(self, s: str) -> str:
d = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
]
i, n = 0, len(s)
ans = []
while i < n:
for j, t in enumerate(d):
m = len(t)
if i + m <= n and s[i : i + m] == t:
ans.append(str(j))
i += m - 1
break
i += 1
return "".join(ans)