zoukankan      html  css  js  c++  java
  • LeetCode 990. 等式方程的可满足性

    题目链接

    990. 等式方程的可满足性

    题目分析

    这个题目其实非常典型的并查集的内容了,我们首先先对等号的式子建立一个并查集。然后再使用一轮循环去判断不等号的情况,如果不等号的左右两个符号属于同一个集合,那么就说明这个式子有问题,返回false即可。否则就返回true。

    代码实现

    class Solution {
        int[] anc = new int[26];
        public boolean equationsPossible(String[] equations) {
            for(int i = 0; i < anc.length; i++){
                anc[i] = i;
            }
            for(String str: equations){
                char a = str.charAt(0);
                char b = str.charAt(3);
                char ops = str.charAt(1);
                if(ops == '='){
                    int anc1 = find(a - 'a');
                    int anc2 = find(b - 'a');
                    anc[anc1] = anc2;
                }
            }
            for(String str: equations){
                char a = str.charAt(0);
                char b = str.charAt(3);
                char ops = str.charAt(1);
                if(ops == '!'){
                    int anc1 = find(a - 'a');
                    int anc2 = find(b - 'a');
                    if(anc1 == anc2){
                        return false;
                    }
                }
            }
            return true;
        }
    
        public int find(int x){
            while(x != anc[x]){
                x = anc[x];
            }
            return x;
        }
    }
    
  • 相关阅读:
    各种小知识
    基础技能
    st表
    有理数取余
    FFT加速高精度乘法
    unique
    离散化
    线段树复杂度分析
    楼房重建
    电脑装系统常用方法
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/13684080.html
Copyright © 2011-2022 走看看