|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目描述:
- 给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
- 只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。 
-  
- 示例 1:
- 输入:["a==b","b!=a"]
- 输出:false
- 解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。
- 示例 2:
- 输出:["b==a","a==b"]
- 输入:true
- 解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。
- 示例 3:
- 输入:["a==b","b==c","a==c"]
- 输出:true
- 示例 4:
- 输入:["a==b","b!=c","c==a"]
- 输出:false
- 示例 5:
- 输入:["c==c","b==d","x!=z"]
- 输出:true
-  
- 提示:
- 1 <= equations.length <= 500
- equations[i].length == 4
- equations[i][0] 和 equations[i][3] 是小写字母
- equations[i][1] 要么是 '=',要么是 '!'
- equations[i][2] 是 '='
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/satisfiability-of-equality-equations
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- class Solution {
- public:
- char find_root(char x, map<char, char>&father){
- if(father[x] != x) return find_root(father[x], father);
- return x;
- }
- void unition(char x, char y, map<char, char>& father, map<char, int>& rank){
- char temp1 = find_root(x, father);
- char temp2 = find_root(y, father);
- if(temp1 != temp2){
- if(rank[temp1] > rank[temp2]){
- father[temp2] = temp1;
- }else if(rank[temp1] <= rank[temp2]){
- if(rank[temp1] == rank[temp2]){
- rank[temp1]++;
- }
- father[temp1] = temp2;
- }
- }
- }
- bool equationsPossible(vector<string>& equations) {
- int len = equations.size();
- set<char> store;
- for(int i = 0 ; i < len; i++){
- store.insert(equations[i][0]);
- store.insert(equations[i][3]);
- }
- vector<char>store1(store.begin(), store.end());
- int len1 = store1.size();
- map<char, char>father;
- map<char, int>rank;
- for(int i = 0; i < len1; i++){
- father[store1[i]] = store1[i];
- rank[store1[i]] = 1;
- }
- for(int i = 0 ; i < len; i ++){
- if(equations[i][1] == '='){
- unition(equations[i][0], equations[i][3], father, rank);
- }
- }
- for(int i = 0; i < len; i++){
- if(equations[i][1] == '!'){
- char temp1 = find_root(equations[i][0], father);
- char temp2 = find_root(equations[i][3], father);
- if(temp1 == temp2) return false;
- }
- }
- return true;
- }
- };
复制代码 |
|