微信小程序选项卡功能开发步骤与方法全解析
573
2022-11-09
LeetCode-990. Satisfiability of Equality Equations
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: falseExplanation: 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: trueExplanation: 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'='
题解:
并查集的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}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~