Leetcode 423. Reconstruct Original Digits from English
Given a non-empty string containing an out-of-order English representation of digits 0-9, reconstruct the digits in ascending order. For example, given “owoztneoer”, output should be “012”.
Here’s the Java code to solve the problem:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public String originalDigits(String s) {
int[] count = new int[10]; // Array to store count of each digit
int[] charCount = new int[26]; // Array to store count of each character
// Count the frequency of each character in the input string
for (char ch : s.toCharArray()) {
charCount[ch - 'a']++;
}
// Identify counts using unique characters
count[0] = charCount['z' - 'a'];
count[2] = charCount['w' - 'a'];
count[4] = charCount['u' - 'a'];
count[6] = charCount['x' - 'a'];
count[8] = charCount['g' - 'a'];
// Identify counts using partially unique characters
count[1] = charCount['o' - 'a'] - count[0] - count[2] - count[4];
count[3] = charCount['h' - 'a'] - count[8];
count[5] = charCount['f' - 'a'] - count[4];
count[7] = charCount['s' - 'a'] - count[6];
count[9] = charCount['i' - 'a'] - count[5] - count[6] - count[8];
// Build the output string from digit counts
StringBuilder result = new StringBuilder();
for (int i = 0; i <= 9; i++) {
for (int j = 0; j < count[i]; j++) {
result.append(i);
}
}
return result.toString();
}
public static void main(String[] args) {
Solution solution = new Solution();
String s = "owoztneoer";
System.out.println(solution.originalDigits(s)); // Output: "012"
}
}
So, the overall time complexity is O(n) and the space complexity is O(1), not counting the input string itself since all auxiliary space usage is either constant or dependent on a fixed range (0-9 digits).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?