leetcode 990. 等式方程的可满足性

110 阅读1分钟

c++

class Solution {
public:
    class UnionSet {
    public:
        int *father, n;
        UnionSet(int n) : n(n) {
            father = new int[n + 1]; 
            for (int i = 0; i <= n; i++) {
                father[i] = i;
            }
        }
        int find(int x) {
            return father[x] = (father[x] == x ? x : find(father[x]));
        }
        void merge(int a, int b) {
            father[find(a)] = find(b);
            return ;
        }
    };
    bool equationsPossible(vector<string>& equations) {
        UnionSet u(26);
        for (string str : equations) {
            if (str[1] == '!') continue;
            u.merge(str[0] - 'a', str[3] - 'a');
        }
        for (string str : equations) {
            if (str[1] == '=') continue;
            if (u.find(str[0] - 'a') == u.find(str[3] - 'a')) return false;
        }
        return true;
    }
};

js

class UnionSet {
    constructor(n) {
        this.father = new Array(n);
        for (var i = 0; i < n; i++) this.father[i] = i;
    }
    find(x) {
        return this.father[x] = (this.father[x] == x ? x : this.find(this.father[x]));
    }
    merge(a, b) {
        this.father[this.find(a)] = this.find(b); 
    } 
};

var equationsPossible = function(equations) {
    var u = new UnionSet(26);
    for (var str of equations) {
        if (str[1] === '!') continue;
        u.merge(str[0].charCodeAt() - 'a'.charCodeAt(), str[3].charCodeAt() - 'a'.charCodeAt());
    }
    for (var str of equations) {
        if (str[1] === '=') continue;
        if (u.find(str[0].charCodeAt() - 'a'.charCodeAt()) == u.find(str[3].charCodeAt() - 'a'.charCodeAt())) 
            return false;
    }
    return true;
};