LeetCode-990. Satisfiability of Equality Equations
原创
©著作权归作者所有:来自51CTO博客作者ReignsDu的原创作品,请联系作者获取转载授权,否则将追究法律责任
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.
Example 1:
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.
Example 2:
Input: ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.
Example 3:
Input: ["a==b","b==c","a==c"]
Output: true
Example 4:
Input: ["a==b","b!=c","c==a"]
Output: false
Example 5:
Input: ["c==c","b==d","x!=z"]
Output: true
Note:
-
1 <= equations.length <= 500
-
equations[i].length == 4
-
equations[i][0]
andequations[i][3]
are lowercase letters -
equations[i][1]
is either'='
or'!'
-
equations[i][2]
is'='
题解:
并查集的unoin, find,先合并所有==,之后查找所有!=。
go:
func union(x, y int, f []int) {
fx := find(x, f)
fy := find(y, f)
if fx != fy {
f[fy] = fx
}
}
func find(x int, f []int) int{
if f[x] != x {
return find(f[x], f)
} else {
return x
}
}
func equationsPossible(equations []string) bool {
f := make([]int, 26)
f[0] = 0
for i := 1; i < 26; i++ {
f[i] = f[i - 1] + 1
}
for _, e := range equations {
if e[1] == '=' {
union(int(e[0] - 'a'), int(e[3] - 'a'), f)
}
}
for _, e := range equations {
if e[1] == '!' {
if find(int(e[0] - 'a'),f) == find (int(e[3] - 'a'), f) {
return false
}
}
}
return true
}