Satisfiability of Equality Equations

Given an array equations of strings that represent relationships between variables, each string equations[i] has length 4 and takes one of two different forms: "a==b" or "a!=b".  Here, a and b are lowercase letters (not necessarily different) that represent one-letter variable names.

Return true if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.

 

Example 1:

Input: ["a==b","b!=a"]
Output: false
Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.  There is no way to assign the variables to satisfy both equations.

Example 2:

Input: ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.

Example 3:

Input: ["a==b","b==c","a==c"]
Output: true

Example 4:

Input: ["a==b","b!=c","c==a"]
Output: false

Example 5:

Input: ["c==c","b==d","x!=z"]
Output: true

 

Note:

  1. 1 <= equations.length <= 500
  2. equations[i].length == 4
  3. equations[i][0] and equations[i][3] are lowercase letters
  4. equations[i][1] is either '=' or '!'
  5. equations[i][2] is '='

题目理解:

给定一系列的相等和不等关系,问所有的式子能否同时成立

解题思路:

使用并查集,不知道的话可以自己百度一下。

遇到等式时,将所有相等的元素union起来,遇到不等式时先不处理,但是记录下来。

遍历所有的式子之后,遍历不等式,如果不等式两端的变量的root是相同的,说明这两个元素在等式当中,又在不等式当中,因此所有的式子不能同时成立。这是一种效率较高的解法。

class Solution {
    int[] root = new int[26];
    public void union(int a, int b){
        root[find(a)] = root[find(b)];
    }
    
    public int find(int num){
        if(root[num] != num)
            root[num] = find(root[num]);
        return root[num];
    }
    
    public boolean equationsPossible(String[] equations) {
        for(int i = 0; i < 26; i++)
            root[i] = i;
        List<String> list = new ArrayList<>();
        for(String str : equations){
            char[] chs = str.toCharArray();
            if(chs[1] == '=')
                union(chs[0] - 'a', chs[3] - 'a');
            else
                list.add(str);
        }
        for(String str : list){
            char[] chs = str.toCharArray();
            if(find(chs[0] - 'a') == find(chs[3] - 'a'))
                return false;
        }
        return true;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值