解方程——423. 从英文中重建数字

题目


OJ平台

解题过程

  • 我们现在是确定了这个肯定是有解的,但就是不清楚具体是哪些数字,所以可根据每个数字的英文,看看哪些字符对应着哪些数字,然后根据一些特定的字符确定某个数字,比如只有 8 eight 含有 g ,所以可以直接确定它的数目。以此类推,得出多个方程组,进行求解!

比如运行下面的代码便可得出字符和数字的对应关系:

    string nums[10] = {
    
    "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    unordered_map<char, vector<int>> occur;

    void pre() {
    
    
        for (int i = 0; i < 10; i++) {
    
    
            string n = nums[i];
            for (auto c: n) {
    
    
                if (occur.count(c) == 0) occur[c] = vector<int>();
                occur[c].push_back(i);
            }
        }

        for (auto p: occur) {
    
    
            cout << p.first << ": ";
            for (auto pos: p.second) {
    
    
                cout << pos << " ";
            }
            cout << endl;
        }
    }

对应关系:

g: 8 
x: 6 
z: 0 
e: 0 1 3 3 5 7 7 8 9 
r: 0 3 4 
o: 0 1 2 4 
n: 1 7 9 9 
t: 2 3 8 
w: 2 
h: 3 8 
u: 4 
f: 4 5 
s: 6 7 
i: 5 6 8 9 
v: 5 7 

可以发现消元求解顺序为:
8 6 0 2 3 4 5 7 9 1

解题代码

class Solution {
    
    
public:
string originalDigits(string s) {
    
    
     int num[10] {
    
    };
        int cnt[26] {
    
    };

        for (auto c: s) {
    
    
            cnt[c-'a']++;
        }

        num[8] = cnt['g'-'a'];
        num[6] = cnt['x'-'a'];
        num[0] = cnt['z'-'a'];
        num[2] = cnt['w'-'a'];
        num[3] = cnt['h'-'a'] - num[8];
        num[4] = cnt['u'-'a'];
        num[5] = cnt['f'-'a'] - num[4];
        num[7] = cnt['s'-'a'] - num[6];
        num[9] = cnt['i'-'a'] - num[5] - num[6] - num[8];
        num[1] = cnt['n'-'a'] - num[7] - 2*num[9];

        string ans = "";
        for (int i = 0; i < 10; i++) {
    
    
            string c = to_string(i);
            while(num[i]) {
    
    
                ans += c;
                num[i]--;
            }
        }

        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_50945504/article/details/121513370