LeetCode423. Reconstruct Original Digits from English

Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.

Note:

  1. Input contains only lowercase English letters.
  2. 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.
  3. Input length is less than 50,000.

 

Example 1:

Input: "owoztneoer"

Output: "012"

 

Example 2:

Input: "fviefuro"

Output: "45"

参考资料:here。

class Solution {
public:
	string originalDigits(string s) {
		string ans;
		vector counts(26, 0), nums(10, 0);
		for (char c : s) counts[c - 'a']++;
		nums[0] = counts['z' - 'a'];
		nums[2] = counts['w' - 'a'];
		nums[4] = counts['u' - 'a'];
		nums[6] = counts['x' - 'a'];
		nums[8] = counts['g' - 'a'];
		nums[1] = counts['o' - 'a'] - nums[0] - nums[2] - nums[4];
		nums[3] = counts['h' - 'a'] - nums[8];
		nums[5] = counts['f' - 'a'] - nums[4];
		nums[7] = counts['s' - 'a'] - nums[6];
		nums[9] = counts['i' - 'a'] - nums[6] - nums[8] - nums[5];
		for (int i = 0; i < nums.size(); i++) {
			for (int j = 0; j < nums[i]; j++) ans += to_string(i);
		}
		return ans;
	}
};

 

你可能感兴趣的:(LeetCode)