【Leetcode】423. Reconstruct Original Digits from English

题目地址:

https://leetcode.com/problems/reconstruct-original-digits-from-english/description/

给定一个长 n n n字符串 s s s,其是若干数字的英文小写单词连接在一起并且打乱顺序所得,要求将其还原为数字组成的字符串,并且数字按升序排列。题目保证答案存在。

我们可以观察哪些字母只在某个数字中出现,然后逐个求出每个数字出现了多少次。先开个哈希表存一下 s s s中每个字母出现了多少次。接着,例如,'z'只在 0 0 0中出现,可以通过看 s s s中有多少个'z'知道 0 0 0有多少个;接着从哈希表中删去 0 0 0的每个字母的所有出现次数,例如'g'只在 8 8 8中出现,和上面一样可以知道 8 8 8有多少个,以此类推。代码如下:

class Solution {
 public:
  string originalDigits(string s) {
    string ss[] = {"zero", "one", "two",   "three", "four",
                   "five", "six", "seven", "eight", "nine"};
    int num[] = {0, 8, 3, 2, 6, 4, 5, 1, 7, 9};
    unordered_map<char, int> mp;
    map<char, int> mp2;
    for (char c : s) mp[c]++;
    string res;
    for (int x : num) {
      int cnt = INT_MAX;
      for (char c : ss[x]) cnt = min(cnt, mp[c]);
      if (!cnt) continue;
      mp2[x + '0'] = cnt;
      for (char c : ss[x]) mp[c] -= cnt;
    }
    for (auto &[k, v] : mp2) res += string(v, k);
    return res;
  }
};

时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)

你可能感兴趣的:(LC,栈,队列,串及其他数据结构,leetcode,算法,c++,数据结构)