解题思路:写一个find函数,其作用是判断字符串是否相似,接着算字符串列表的长度,再把每一个字符串做比较,若相似,则归为一组,否则在另一组。
源代码:
class Solution {
public:
int numSimilarGroups(vector<string>& strs) {
int n = strs.size();
int m = strs[0].size();
for (int i = 1; i <= n; ++i) p[i] = i;
int res = 0;
for (int i = 0; i < n - 1; ++i)
for (int j = i + 1; j < n; ++j) {
if (find(i + 1) != find(j + 1)) {
int cnt = 0;
for (int k = 0; k < m; ++k) if (strs[i][k] != strs[j][k]) ++cnt;
if (cnt == 0 || cnt == 2) p[find(i + 1)] = find(j + 1);
}
}
for (int i = 1; i <= n; ++i) if (p[i] == i) ++res;
return res;
}
private:
vector<int> p = vector<int> (310, 0);
int find(int x) {
if (x != p[x]) p[x] = find(p[x]);
return p[x];
}
};
运行结果:
示例1:
示例2: