Reconstruct Original Digits from English in C++

C++Server Side ProgrammingProgramming

Suppose we have a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. There are some properties −

  • Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.
  • Input length is less than 50,000.

So if the input is like “fviefuro”, then the output will be 45.

To solve this, we will follow these steps −

  • nums := an array that is holding the numbers in English letter from 0 to 9.
  • make one array count of size 10
  • ans := an empty string. and n := size of the string.
  • for i in range 0 to n – 1, do
    • if s[i] = ‘z’, then increase count[0] by 1
    • if s[i] = ‘w’, then increase count[2] by 1
    • if s[i] = ‘g’, then increase count[8] by 1
    • if s[i] = ‘x’, then increase count[6] by 1
    • if s[i] = ‘v’, then increase count[5] by 1
    • if s[i] = ‘o’, then increase count[1] by 1
    • if s[i] = ‘s’, then increase count[7] by 1
    • if s[i] = ‘f’, then increase count[4] by 1
    • if s[i] = ‘h’, then increase count[3] by 1
    • if s[i] = ‘i’, then increase count[9] by 1
  • count[7] := count[7] – count[6]
  • count[5] := count[5] – count[7]
  • count[4] := count[4] – count[5]
  • count[1] := count[1] – (count[2] + count[4] + count[0])
  • count[3] := count[3] – count[8]
  • count[9] := count[9] – (count[5] + count[6] + count[8])
  • for i in range 0 to 9, do
    • for j in range 0 to count[i]
      • ans := ans + character of (i + ‘0’)
  • return ans

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string originalDigits(string s) {
      string nums[]= {"zero", "one", "two", "three", "four", "five", "six", "seven","eight", "nine"};
      vector <int> cnt(10);
      string ans = "";
      int n = s.size();
      for(int i = 0; i < n; i++){
         if(s[i] == 'z')cnt[0]++;
         if(s[i] == 'w') cnt[2]++;
         if(s[i] == 'g')cnt[8]++;
         if(s[i] == 'x')cnt[6]++;
         if(s[i] == 'v')cnt[5]++;
         if(s[i] == 'o')cnt[1]++;
         if(s[i] == 's')cnt[7]++;
         if(s[i] == 'f')cnt[4]++;
         if(s[i] == 'h')cnt[3]++;
         if(s[i] == 'i') cnt[9]++;
      }
      cnt[7] -= cnt[6];
      cnt[5] -= cnt[7];
      cnt[4] -= cnt[5];
      cnt[1] -= (cnt[2] + cnt[4] + cnt[0]);
      cnt[3] -= cnt[8];
      cnt[9] -= (cnt[5] + cnt[6] + cnt[8]);
      for(int i = 0; i < 10; i++){
         for(int j = 0; j < cnt[i]; j++){
            ans += (char)(i + '0');
         }
      }
      return ans;
   }
};
main(){
   Solution ob;
   cout << ob.originalDigits("fviefuro");
}

Input

"fviefuro"

Output

"45"
raja
Updated on 28-Apr-2020 12:32:27

Advertisements