友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

990. 等式方程的可满足性

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

只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false

示例 1:

输入:["a==b","b!=a"]
输出:false
解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。

示例 2:

输入:["b==a","a==b"]
输出:true
解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。

示例 3:

输入:["a==b","b==c","a==c"]
输出:true

示例 4:

输入:["a==b","b!=c","c==a"]
输出:false

示例 5:

输入:["c==c","b==d","x!=z"]
输出:true

提示:

  1. 1 <= equations.length <= 500

  2. equations[i].length == 4

  3. equations[i][0]equations[i][3] 是小写字母

  4. equations[i][1] 要么是 =,要么是 !

  5. equations[i][2]=

思路分析

并查集。

将式子分成按照是否相等分成两类,先将等式部分在并查集中建立链接,然后遍历不等式,查看不等式的元素是否相连,相连就会出现矛盾,就不满足要求。否则就是 OK 的。

  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2025-09-20 23:06:36
 */
public boolean equationsPossible(String[] equations) {
  List<String> equationsList = new ArrayList<>();
  List<String> noEquationsList = new ArrayList<>();
  for (String equation : equations) {
    if (equation.charAt(1) == '=') {
      equationsList.add(equation);
    } else {
      noEquationsList.add(equation);
    }
  }
  UnionFind graph = new UnionFind(26);
  for (String equation : equationsList) {
    int a = equation.charAt(0) - 'a';
    int b = equation.charAt(3) - 'a';
    graph.union(a, b);
  }
  for (String equation : noEquationsList) {
    int a = equation.charAt(0) - 'a';
    int b = equation.charAt(3) - 'a';
    boolean connected = graph.isConnected(a, b);
    if (connected) {
      return false;
    }
  }
  return true;
}

public static class UnionFind {
  private int[] parent;

  public UnionFind(int n) {
    parent = new int[n];
    for (int i = 0; i < n; i++) {
      parent[i] = i;
    }
  }

  public int find(int x) {
    int xp = parent[x];
    if (xp != x) {
      List<Integer> path = new ArrayList<>();
      path.add(x);
      while (xp != parent[xp]) {
        path.add(parent[xp]);
        xp = parent[xp];
      }
      for (Integer p : path) {
        parent[p] = xp;
      }
    }
    return xp;
  }

  public void union(int a, int b) {
    int ap = find(a);
    int bp = find(b);
    if (ap == bp) {
      return;
    }
    parent[ap] = bp;
  }

  public boolean isConnected(int a, int b) {
    return find(a) == find(b);
  }
}