LeetCode //C - 423. Reconstruct Original Digits from English

423. Reconstruct Original Digits from English

Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.
 

Example 1:

Input: s = “owoztneoer”
Output: “012”

Example 2:

Input: s = “fviefuro”
Output: “45”

Constraints:
  • 1 < = s . l e n g t h < = 1 0 5 1 <= s.length <= 10^5 1<=s.length<=105
  • s[i] is one of the characters [“e”,“g”,“f”,“i”,“h”,“o”,“n”,“s”,“r”,“u”,“t”,“w”,“v”,“x”,“z”].
  • s is guaranteed to be valid.

From: LeetCode
Link: 423. Reconstruct Original Digits from English


Solution:

Ideas:
  1. Frequency Counting: We first count the frequency of each letter in the input string.
  2. Unique Character Identification: Based on the unique characters ‘z’, ‘w’, ‘u’, ‘x’, and ‘g’, we directly identify the digits 0, 2, 4, 6, and 8.
  3. Deducing Other Digits: After subtracting counts for the above digits, we use remaining characters like ‘o’, ‘h’, ‘f’, ‘s’, and ‘i’ to deduce digits 1, 3, 5, 7, and 9.
  4. Building the Result: We construct the result string by appending the identified digits in ascending order.
Code:
char* originalDigits(char* s) {
    
    
    int count[10] = {
    
    0};  // To store the count of each digit
    int freq[26] = {
    
    0};   // To store the frequency of each letter
    
    // Count the frequency of each character in the input string
    for (int i = 0; s[i] != '\0'; i++) {
    
    
        freq[s[i] - 'a']++;
    }

    // Identify digits using unique letters
    count[0] = freq['z' - 'a']; // 'z' is unique to "zero"
    count[2] = freq['w' - 'a']; // 'w' is unique to "two"
    count[4] = freq['u' - 'a']; // 'u' is unique to "four"
    count[6] = freq['x' - 'a']; // 'x' is unique to "six"
    count[8] = freq['g' - 'a']; // 'g' is unique to "eight"
    
    // Now use the remaining characters to identify other digits
    count[1] = freq['o' - 'a'] - count[0] - count[2] - count[4]; // 'o' is in "one"
    count[3] = freq['h' - 'a'] - count[8]; // 'h' is in "three" after "eight" is removed
    count[5] = freq['f' - 'a'] - count[4]; // 'f' is in "five" after "four" is removed
    count[7] = freq['s' - 'a'] - count[6]; // 's' is in "seven" after "six" is removed
    count[9] = freq['i' - 'a'] - count[5] - count[6] - count[8]; // 'i' is in "nine"

    // Construct the output string
    char* result = (char*)malloc(100001 * sizeof(char)); // Max length is 100,000 + 1
    int index = 0;
    for (int i = 0; i <= 9; i++) {
    
    
        for (int j = 0; j < count[i]; j++) {
    
    
            result[index++] = '0' + i;
        }
    }
    result[index] = '\0';  // Null terminate the string

    return result;
}

猜你喜欢

转载自blog.csdn.net/navicheung/article/details/143102970