Reconstruct Original Digits from English 从英文中重建数字

给定一个非空字符串,其中包含字母顺序打乱的英文单词表示的数字0-9。按升序输出原始的数字。

注意:

  1. 输入只包含小写英文字母。
  2. 输入保证合法并可以转换为原始的数字,这意味着像 "abc" 或 "zerone" 的输入是不允许的。
  3. 输入字符串的长度小于 50,000。

示例 1:

输入: "owoztneoer"

输出: "012" (zeroonetwo)

示例 2:

输入: "fviefuro"

输出: "45" (fourfive),

思路:由于给定的字符串是无序的,且保证输入是有效的,所以只要找到每一个数字的“独特标识”即可(换句话说,每个数字只需要一个字母就可以唯一代替),那么只要从0开始到9,统计各个唯一字母的次数就可以了。

具体如下图所示,每个字母在所有子母中出现的次数统计:

先统计次数为1的,然后是2的,然后3,以此类推。。。

参考代码:

class Solution {
public:
string originalDigits(string s) {
	vector<int> counts(10, 0);
	for (char c : s) {
		if (c == 'z') counts[0]++;
		if (c == 'w') counts[2]++;
		if (c == 'g') counts[8]++;
		if (c == 'u') counts[4]++;
		if (c == 'x') counts[6]++;
		if (c == 's') counts[7]++; //7-6
		if (c == 'f') counts[5]++; //5-4
		if (c == 'h') counts[3]++; //3-8
		if (c == 'i') counts[9]++; //9-8-5-6
		if (c == 'o') counts[1]++; //1-0-2-4
	}
	counts[7] -= counts[6];
	counts[5] -= counts[4];
	counts[3] -= counts[8];
	counts[9] = counts[9]- counts[8] - counts[5] - counts[6];
	counts[1] = counts[1] - counts[0] - counts[2] - counts[4];
	string result = "";
	for (int i = 0; i < 10; i++) {
		while (counts[i] > 0) {
			result.push_back(i + '0');
			counts[i]--;
		}
	}
	return result;
}
};

猜你喜欢

转载自blog.csdn.net/qq_26410101/article/details/85489664
今日推荐