LeetCode 990. Satisfiability of Equality Equations
原题链接在这里:https://leetcode.com/problems/satisfiability-of-equality-equations/ 题目: Given an array?equations?of strings that represent relationships between variables,each string? Return? 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:
题解: First,go through equations,union all with "==". Then,go through equations again,if a!=b,but a and b are in the same union,then return false. Time Complexity: O(nlogk). n = equations.length. k is number distinct character. Since k is single lower case,thus k <= 26. Space: O(k). AC Java: 1 class Solution { 2 HashMap<Character,Character> parent; 3 4 public boolean equationsPossible(String[] equations) { 5 if(equations == null || equations.length == 0){ 6 return true; 7 } 8 9 parent = new HashMap<>(); 10 for(String s : equations){ 11 if(s.substring(1,3).equals("==")){ 12 union(s.charAt(0),s.charAt(3)); 13 } 14 } 15 16 for(String s : equations){ 17 if(s.substring(1,3).equals("!=") && find(s.charAt(0))==find(s.charAt(3))){ 18 return false; 19 } 20 } 21 22 return true; 23 } 24 25 private void union(char i,char j){ 26 char p = find(i); 27 char q = find(j); 28 if(p != q){ 29 parent.put(p,q); 30 } 31 } 32 33 private char find(char c){ 34 parent.putIfAbsent(c,c); 35 if(parent.get(c) != c){ 36 char ancestor = find(parent.get(c)); 37 parent.put(c,ancestor); 38 } 39 40 return parent.get(c); 41 } 42 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |