题目来源
给一个字符串,由顺序混乱的英文字母数字组成,然后求将其复原后的情况。
我用了有点取巧的方法,就是按顺序来,因为这些个英文数字的字母可以区分这些数字,代码如下:
class Solution {
public:
string originalDigits(string s) {
int n = s.size();
vector<int> chaCnt(26, 0);
for (int i=0; i<n; i++)
chaCnt[s[i]-'a']++;
vector<char> primes{'z', 'x', 's', 'u', 'f', 'h', 'i', 'w', 't', 'n'};
vector<string> nums{"zero", "six", "seven", "four", "five", "eight", "nine", "two", "three", "one"};
vector<int> digits{0, 6, 7, 4, 5, 8, 9, 2, 3, 1};
vector<int> cnt(10, 0);
for (int i=0; i<10; i++) {
int tmp = chaCnt[primes[i]-'a'];
for (int j=0; j<nums[i].size(); j++)
tmp = min(tmp, chaCnt[nums[i][j]-'a']);
for (int j=0; j<nums[i].size(); j++)
chaCnt[nums[i][j]-'a'] -= tmp;
cnt[digits[i]] = tmp;
}
string res = "";
for (int i=0; i<10; i++) {
for (int j=0; j<cnt[i]; j++)
res += to_string(i);
}
return res;
}
};
发现方法都差不多,不过答案比我简洁些。
代码如下:
string originalDigits(string s) {
vector<int> a(10, 0);
vector<int> alpha(128, 0);
for (char c : s)
alpha[c]++;
a[0] = alpha['z'];
a[2] = alpha['w'];
a[4] = alpha['u'];
a[6] = alpha['x'];
a[8] = alpha['g'];
a[3] = alpha['h'] - a[8];
a[5] = alpha['f'] - a[4];
a[7] = alpha['v'] - a[5];
a[1] = alpha['o'] - a[0] - a[2] - a[4];
a[9] = alpha['i'] - a[5] - a[6] - a[8];
string ans;
for (int i = 0; i < 10; i++) {
if (a[i] > 0)
ans += string(a[i], '0' + i);
}
return ans;
}