題目
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 <= 500equations[i].length == 4equations[i][0]andequations[i][3]are lowercase lettersequations[i][1]is either'='or'!'equations[i][2]is'='
題目大意
給定一個由表示變量之間關係的字符串方程組成的數組,每個字符串方程 equations[i] 的長度為 4,並採用兩種不同的形式之一:"a==b" 或 "a!=b"。在這裏,a 和 b 是小寫字母(不一定不同),表示單字母變量名。只有當可以將整數分配給變量名,以便滿足所有給定的方程時才返回 true,否則返回 false。
提示:
- 1 <= equations.length <= 500
- equations[i].length == 4
- equations[i][0] 和 equations[i][3] 是小寫字母
- equations[i][1] 要麼是 '=',要麼是 '!'
- equations[i][2] 是 '='
解題思路
- 給出一個字符串數組,數組裏面給出的是一些字母的關係,只有
'=='和'! ='兩種關係。問給出的這些關係中是否存在悖論? - 這一題是簡單的並查集的問題。先將所有
'=='關係的字母union()起來,然後再一一查看'! ='關係中是否有'=='關係的組合,如果有,就返回false,如果遍歷完都沒有找到,則返回true。 e`。
參考代碼
package leetcode
import (
"github.com/halfrost/LeetCode-Go/template"
)
func equationsPossible(equations []string) bool {
if len(equations) == 0 {
return false
}
uf := template.UnionFind{}
uf.Init(26)
for _, equ := range equations {
if equ[1] == '=' && equ[2] == '=' {
uf.Union(int(equ[0]-'a'), int(equ[3]-'a'))
}
}
for _, equ := range equations {
if equ[1] == '!' && equ[2] == '=' {
if uf.Find(int(equ[0]-'a')) == uf.Find(int(equ[3]-'a')) {
return false
}
}
}
return true
}