原题链接在这里:https://leetcode.com/problems/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: 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: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.

Example 3:

Input: true

Example 4:

Input: false

Example 5:

Input: true

Note:

  1. 1 <= equations.length <= 500
  2. equations[i].length == 4
  3. equations[i][0] and equations[i][3] are lowercase letters
  4. equations[i][1] is either '=' or '!'
  5. equations[i][2] is '='

题解:

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 }

 

相关文章:

  • 2022-03-09
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
  • 2021-12-17
  • 2021-07-16
  • 2022-12-23
猜你喜欢
  • 2021-06-03
  • 2021-12-26
  • 2021-08-18
  • 2022-12-23
  • 2021-11-30
  • 2021-06-13
  • 2022-01-18
相关资源
相似解决方案