Leetcode 990. 等式方程的可满足性 并查集

53 阅读1分钟

990. 等式方程的可满足性 - 力扣(LeetCode)

思想

题目要求我们不能相悖,也就是a=b,a!=b,那么就矛盾了, return false;

我们可以通过看下标1位置的字符是'='还是'!'来是否相等image.png

相等和不相等都有对应的处理方案

相等

如果相等,那么就把它们加为一个集合。

不相等

如果不相等但是却在一个集合,那么就返回false,如果不相等,但是却不在一个集合,那么就返回true;

code

class Solution {
public:
    bool equationsPossible(vector<string>& equations) {
    vector<int> ufs(26,-1);//小写字母ASCII建立映射

    //找根
   auto  findRoot=[&ufs](int x)
    {
        if(ufs[x]>=0)//编码0就不是根
         x=ufs[x];//把编码给给x,再通过ufs[x]就可以找到对应的父节点
    return x;
    };
         //合并  第一种情况,如果值相等的情况下
         for(auto& str:equations)//遍历一遍字符串
         {
             //判断是否相等,相等就合并为一个集合
             if(str[1]=='=')//说明相等
             {   //相等就合并
                 int root1=findRoot(str[3]-'a');
                 int root2=findRoot(str[0]-'a');
                 ufs[root1]+=ufs[root2];
                 ufs[root2]=root1;
             }
         }


          //合并  第二种情况,如果不相等但是却在一个集合,那么就相悖
         for(auto& str:equations)
         {
             //判断是否相等,相等就合并为一个集合
             if(str[1]=='!')//说明不相等
             {
                 int root1=findRoot(str[3]-'a');
                 int root2=findRoot(str[0]-'a');
                 if(root1==root2)return false;//不相等还在一个集合就返回false
             }
         }
  
  return true;
    }
};