一、Problem
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.
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.
二、Solution
方法一:UF
class Solution {
int n, a[];
void union(int p, int q) {
int pp = find(p), qq = find(q);
if (pp == qq)
return;
a[pp] = qq;
}
int find(int p) {
while (a[p] != a[a[p]]) {
a[p] = a[a[p]];
}
return a[p];
}
public boolean equationsPossible(String[] es) {
n = es.length;
a = new int[26];
for (int i = 0; i < a.length; i++) a[i] = i;
for (String e : es) {
for (int i = 0; i < e.length(); i++) {
int a = e.charAt(0)-'a', b = e.charAt(3)-'a';
if (e.charAt(1) == e.charAt(2))
union(a, b);
}
}
for (String e : es) {
for (int i = 0; i < e.length(); i++) {
int a = e.charAt(0)-'a', b = e.charAt(3)-'a';
if (e.charAt(1) != e.charAt(2) && find(a) == find(b))
return false;
}
}
return true;
}
}
小優化:如果有 == 纔去 union,如果有 != 時才比較兩個變量的父親是否相同。
class Solution {
int n, a[], sz[];
void union(int p, int q) {
int pp = find(p), qq = find(q);
if (pp == qq)
return;
if (sz[pp] > sz[qq]) {
a[qq] = pp;
sz[pp] += sz[qq];
} else {
a[pp] = qq;
sz[qq] += sz[pp];
}
}
int find(int p) {
while (p != a[p]) {
a[p] = a[a[p]];
p = a[p];
}
return p;
}
public boolean equationsPossible(String[] es) {
n = es.length;
a = new int[26];
sz = new int[26];
for (int i = 0; i < a.length; i++) a[i] = i;
for (String e : es)
for (int i = 0; i < e.length(); i++) if (e.charAt(1) == '=') {
int a = e.charAt(0)-'a', b = e.charAt(3)-'a';
if (e.charAt(1) == e.charAt(2))
union(a, b);
}
for (String e : es)
for (int i = 0; i < e.length(); i++) if (e.charAt(1) == '!') {
int a = e.charAt(0)-'a', b = e.charAt(3)-'a';
if (e.charAt(1) != e.charAt(2) && find(a) == find(b))
return false;
}
return true;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,