題目
給定一個由表示變量之間關係的字符串方程組成的數組,每個字符串方程 equations[i] 的長度爲 4,並採用兩種不同的形式之一:“a==b” 或 “a!=b”。在這裏,a 和 b 是小寫字母(不一定不同),表示單字母變量名。
只有當可以將整數分配給變量名,以便滿足所有給定的方程時才返回 true,否則返回 false。
示例 1:
輸入:["a==b","b!=a"]
輸出:false
解釋:如果我們指定,a = 1 且 b = 1,那麼可以滿足第一個方程,但無法滿足第二個方程。沒有辦法分配變量同時滿足這兩個方程。
示例 2:
輸出:["b==a","a==b"]
輸入:true
解釋:我們可以指定 a = 1 且 b = 1 以滿足滿足這兩個方程。
示例 3:
輸入:["a==b","b==c","a==c"]
輸出:true
示例 4:
輸入:["a==b","b!=c","c==a"]
輸出:false
示例 5:
輸入:["c==c","b==d","x!=z"]
輸出:true
提示:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0] 和 equations[i][3] 是小寫字母
equations[i][1] 要麼是 ‘=’,要麼是 ‘!’
equations[i][2] 是 ‘=’
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/satisfiability-of-equality-equations
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
基本思想:
這道題主要用到一種數據結構:並查集,顧名思義,並:合併,查:查詢當前節點的根
推薦一個並查集的視頻:https://www.bilibili.com/video/BV13t411v7Fs
本題的思想:
- 首先遍歷一遍數組,將相等的合併
- 讓後再遍歷一遍數組,將不等的進行判斷,如果不等的有相同的根直接返回false
class Solution {
private:
vector<int> parent;//記錄父節點
vector<int> rank;//壓縮路徑
public:
Solution(): parent(26, -1), rank(26, 0){}//這裏要特別注意,不能在private中對其初始化
bool equationsPossible(vector<string>& equations) {
for(auto e : equations){//首先將相等的進行合併
if(e[1] == '=' && e[0] - 'a' != e[3] - 'a'){
union_root(e[0] - 'a', e[3] - 'a');
}
}
for(auto e : equations){//判斷不等的是否在兩個不同的集合中
if(e[1] == '!'){
int p_1 = find_root(e[0] - 'a');
int p_2 = find_root(e[3] - 'a');
if(p_1 == p_2)
return false;
}
}
return true;
}
int find_root(int x){
int parent_of_x = x;
while(parent[parent_of_x] != -1)
parent_of_x = parent[parent_of_x];
return parent_of_x;
}
bool union_root(int x, int y){
int parent_of_x = find_root(x);
int parent_of_y = find_root(y);
if(parent_of_x == parent_of_y && parent_of_x != -1 && parent_of_y != -1)
return false;
if(rank[parent_of_x] > rank[parent_of_y]){
parent[parent_of_y] = parent_of_x;
}
else if(rank[parent_of_x] < rank[parent_of_y]){
parent[parent_of_x] = parent_of_y;
}
else{
parent[parent_of_y] = parent_of_x;
rank[parent_of_x]++;
}
return true;
}
};