LeetCode 423: Reconstruct Original Digits from English Solution
Master LeetCode problem 423 (Reconstruct Original Digits from English), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
423. Reconstruct Original Digits from English
Problem Explanation
Explanation
To solve this problem, we can analyze the unique characters present in each number's English representation and use that information to reconstruct the original digits.
We can count the occurrences of unique characters in the input string s and then infer the count of each digit based on the presence of unique characters. For example, the digit '0' is uniquely represented by the character 'z', so if we find 'z' in the input string, we know there must be a '0' in the output. Similarly, the digit '2' is uniquely represented by the character 'w', and so on.
By identifying unique characters for each digit, we can determine the count of each digit in the output string.
Solution Code
class Solution {
public String originalDigits(String s) {
int[] count = new int[10];
for (char ch : s.toCharArray()) {
if (ch == 'z') count[0]++;
if (ch == 'w') count[2]++;
if (ch == 'x') count[6]++;
if (ch == 'g') count[8]++;
if (ch == 'u') count[4]++;
if (ch == 'f') count[5]++; // also contains '4'
if (ch == 'h') count[3]++; // also contains '8'
if (ch == 's') count[7]++; // also contains '6'
if (ch == 'i') count[9]++; // also contains '5', '6', '8'
if (ch == 'o') count[1]++; // also contains '0', '2', '4'
}
count[5] -= count[4];
count[3] -= count[8];
count[7] -= count[6];
count[9] -= (count[5] + count[6] + count[8]);
count[1] -= (count[0] + count[2] + count[4]);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < count[i]; j++) {
sb.append(i);
}
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 423 (Reconstruct Original Digits from English)?
This page provides optimized solutions for LeetCode problem 423 (Reconstruct Original Digits from English) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 423 (Reconstruct Original Digits from English)?
The time complexity for LeetCode 423 (Reconstruct Original Digits from English) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 423 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 423 in Java, C++, or Python.