每日打卡:等式方程的可满足性

打卡:等式方程的可满足性

说在开头

要坚持刷题呀,坚持表达解题的思路,记录为了减少程序复杂度的每一点努力。
“说不定我一生涓滴意念,侥幸汇成河。”

读题

leetcode: 990. 等式方程的可满足性

描述:
给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:“a==b” 或 “a!=b”。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。

测试用例:
输入:[“a==b”,“b!=a”]
输出:false
输出:[“b==a”,“a==b”]
输入:true
输入:[“a==b”,“b==c”,“a==c”]
输出:true
输入:[“a==b”,“b!=c”,“c==a”]
输出:false
输入:[“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] 是 ‘=’

乍一看题目,这是在考啥,完全没有思路啊。这个时候,打开题目的相关标签:并查集
emmm,得涨一波知识了。 并查集详解(超级简单有趣~~就学会了)
大佬给出详细的图解,理解起来很容易。

思路

1:区分 ==!=
2:将 == 左右的元素指向同一个元素
3:用 != 来判断左右的元素是否指向同一个元素

实现

	/**
     * @param equations
     * @return
     */
    public boolean equationsPossible(String[] equations) {
        //将入参分组,==和!=
        List<String> equals = new ArrayList<>();
        List<String> notEquals = new ArrayList<>();
        for (String str : equations) {
            if (str.contains("!")) {
                notEquals.add(str);
            } else {
                equals.add(str);
            }
        }
        //key为自身,value为根元素
        Map<String, String> map = new HashMap<>();
        equals.forEach(e -> putInMap(e.substring(0, 1), e.substring(3, 4), map));
        //至此,所有的i==j均实现了i、j为key,value为同一个元素
        for (String str : notEquals) {
            String left = str.substring(0, 1);
            String right = str.substring(3, 4);
            //判断是否有相同的value
            if(map.computeIfAbsent(left,v->left).equals(map.computeIfAbsent(right,v->right))){
                return false;
            }
        }
        return true;
    }

    /**
     * 将left,right设置到map中,value对应同一个根
     * @param left 等式左侧元素
     * @param right 等式右侧元素
     * @param map 存放并查集的map
     * @return
     */
    public void putInMap(String left, String right, Map<String, String> map) {
        String leftValue = map.computeIfAbsent(left, v -> left);
        String rightValue = map.computeIfAbsent(right, v -> null);
        //若leftValue != rightValue,需要进行合并处理
        if (!leftValue.equals(rightValue)) {
            //将right对应的一系列k-v转为left的v
            if(rightValue!=null){
                map.keySet().forEach(e->{
                    if(map.get(e).equals(rightValue)){
                        map.put(e,leftValue);
                    }
                });
            }else{
                map.put(right,leftValue);
            }
        }
    }

自测

在这里插入图片描述

提交

在这里插入图片描述
实惨,却是意料之中的结果,接下来就是对代码的优化了。

标答

public boolean equationsPossible(String[] equations) {
        int length = equations.length;
        //元素均是小写字母,故数组定长为26
        int[] parent = new int[26];
        for (int i = 0; i < 26; i++) {
            parent[i] = i;
        }
        //先处理==
        for (String str : equations) {
            if (str.charAt(1) == '=') {
                //由小写字母得到的思路:通过ascii增量将字母转为0~25数字,刚好对应
                int index1 = str.charAt(0) - 'a';
                int index2 = str.charAt(3) - 'a';
                union(parent, index1, index2);
            }
        }
        //再处理!=
        for (String str : equations) {
            if (str.charAt(1) == '!') {
                int index1 = str.charAt(0) - 'a';
                int index2 = str.charAt(3) - 'a';
                if (find(parent, index1) == find(parent, index2)) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * index2的掌门决定当index1的掌门的上级
     * @param parent
     * @param index1
     * @param index2
     */
    public void union(int[] parent, int index1, int index2) {
        parent[find(parent, index1)] = find(parent, index2);
    }

    /**
     * 寻找掌门人
     * @param parent
     * @param index
     * @return
     */
    public int find(int[] parent, int index) {
        //parent[index] == index 自我管理:视为掌门
        while (parent[index] != index) {
            //将index上级的上级更新为index的上级--压缩路径
            parent[index] = parent[parent[index]];
            //此时更新index的值,从上级的上级开始向上查
            index = parent[index];
        }
        return index;
    }

find方法在寻找掌门的过程中,将所有涉及的成员都指向了更上一级(注意,此处还未指向掌门)。
union方法绑定了两个元素之间的关系,find的过程中又将成员指向了更上一级。
影响理解的点:parent数组每find一次就优化一次,说不定最终也没优化到最理想的结果呢!

上述代码是我从 官方题解 里copy出来,自己做不到这么精简呀。

实在不知道该怎么程序化地描述方法在做啥,还好大佬贴子中有门派之说,借鉴过来就很好理解了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值