用C++從英文單詞重構原始數字


假設我們有一個非空字串,其中包含0-9數字的無序英文表示,請輸出按升序排列的數字。有一些屬性:

  • 輸入保證有效,可以轉換為其原始數字。這意味著不允許使用諸如“abc”或“zerone”之類的無效輸入。
  • 輸入長度小於50,000。

因此,如果輸入類似於“fviefuro”,則輸出將為45。

為了解決這個問題,我們將遵循以下步驟:

  • nums:一個數組,包含從0到9的英文數字。
  • 建立一個大小為10的計數陣列。
  • ans:一個空字串。n:字串的大小。
  • 對於範圍0到n-1的i,執行:
    • 如果s[i] = 'z',則將count[0]加1
    • 如果s[i] = 'w',則將count[2]加1
    • 如果s[i] = 'g',則將count[8]加1
    • 如果s[i] = 'x',則將count[6]加1
    • 如果s[i] = 'v',則將count[5]加1
    • 如果s[i] = 'o',則將count[1]加1
    • 如果s[i] = 's',則將count[7]加1
    • 如果s[i] = 'f',則將count[4]加1
    • 如果s[i] = 'h',則將count[3]加1
    • 如果s[i] = 'i',則將count[9]加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])
  • 對於範圍0到9的i,執行:
    • 對於範圍0到count[i]的j,執行:
      • ans := ans + (i + '0')對應的字元
  • 返回ans

示例(C++)

讓我們來看下面的實現,以便更好地理解:

 線上演示

#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");
}

輸入

"fviefuro"

輸出

"45"

更新於:2020年4月28日

348 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.