893. Groups of Special-Equivalent Strings

本文详细解析了如何通过算法识别特殊等价字符串组,关键在于区分奇数位置和偶数位置的字符,通过排序并比较来确定字符串是否属于同一组。提供了完整的C++代码实现,包括主函数和解决方案类,演示了如何处理多种输入情况。

Example 1:

Input: ["a","b","c","a","c","c"]
Output: 3
Explanation: 3 groups ["a","a"], ["b"], ["c","c","c"]
Example 2:

Input: ["aa","bb","ab","ba"]
Output: 4
Explanation: 4 groups ["aa"], ["bb"], ["ab"], ["ba"]
Example 3:

Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
Explanation: 3 groups ["abc","cba"], ["acb","bca"], ["bac","cab"]
Example 4:

Input: ["abcd","cdab","adcb","cbad"]
Output: 1
Explanation: 1 group ["abcd","cdab","adcb","cbad"]

Note:

1 <= A.length <= 1000
1 <= A[i].length <= 20
All A[i] have the same length.
All A[i] consist of only lowercase letters.

 

关键在于理解题意。奇数位置字母相同(顺序可以不同),偶数位置字母相同(顺序可以不同),即认为是special-equivalent string。

 

#include<vector>
#include <cstdlib>
#include<iostream>
#include <unordered_set>
#include <algorithm>

using namespace std;

class Solution {
public:
    int numSpecialEquivGroups(vector<string> &A) {
        int res = 0;
        unordered_set<string> st;
        for (int i = 0; i < A.size(); ++i) {
            string odd = "";
            string even = "";
            for (int j = 0; j < A[i].size(); ++j) {
                if (j % 2 == 0)
                    odd += A[i][j];
                else
                    even += A[i][j];
            }
            sort(odd.begin(), odd.end());
            sort(even.begin(), even.end());
            if (st.find(odd + even) == st.end()) {
                res++;
                st.insert(odd + even);
            }
        }
        return res;
    }
};


int main() {
    Solution solution;
    vector<string> A1 = {"abcd", "cdab", "adcb", "cbad"};
    vector<string> A2 = {"abc", "acb", "bac", "bca", "cab", "cba"};
    int res1 = solution.numSpecialEquivGroups(A1);
    int res2 = solution.numSpecialEquivGroups(A2);

    std::cout << "res1: " << res1 << endl;
    std::cout << "res2: " << res2 << endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/learning-c/p/9787578.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值