• 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;
        }
    }
    
  • 相关阅读:
    servlet+jsp结合完成加法运算
    Servlet入门
    java之二叉树算法
    Session
    cookie
    jsp之jstl
    《HDAO》
    《Zoom An Image With Different Interpolation Types》
    《SSAO》
    《debug unreal engine code》
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/13684080.html
Copyright © 2020-2023  润新知