1657. Determine if Two Strings Are Close

题目:

Two strings are considered close if you can attain one from the other using the following operations:

  • Operation 1: Swap any two existing characters.
    • For example, abcde -> aecdb
  • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
    • For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)

You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

Example 1:

Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"

Example 2:

Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.

Example 3:

Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"

Example 4:

Input: word1 = "cabbba", word2 = "aabbss"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any amount of operations.

Constraints:

  • 1 <= word1.length, word2.length <= 10^5
  • word1 and word2 contain only lowercase English letters.

思路:

这道题看上去有点花里胡哨,但是大概是Contest第二题的样子,所有理论上不会太难。读完题目我们可以用三个条件来制约给定的两个数组,以此判断他们是否close。首先长度肯定要一样;其次因为我们关心的是字符以及字符出现的次数,顺序无关紧要,所以我们可以sort。对于出现的字符,我们set来记录;而字符出现的次数,因为是一个一直要改变的key(每次出现已出现字符,次数需要加一),因此用set就不太合适,但是如果用hash map,在比较的时候又不好sort(我们只需要sort次数,而对应次数是什么字符我们并不在意),同时考虑到总共也就只有26个字母,可以直接用vector来记录频次,只要用当前字符减去'a'就是当前字符在vector中的index--有一点点像简易版hashmap。最后只要保证sort完的两个vector和set都相同即可。

代码:

class Solution {
public:
    bool closeStrings(string word1, string word2) {
        int len1=word1.size();
        int len2=word2.size();
        if(len1!=len2)
            return 0;
        set<char> s1, s2;
        vector<int> fre1(26), fre2(26);
        for(auto c:word1)
        {
            s1.insert(c);
            fre1[c-'a']++;
        }
        for(auto c:word2)
        {
            s2.insert(c);
            fre2[c-'a']++;
        }        
        sort(fre1.begin(),fre1.end());
        sort(fre2.begin(),fre2.end());
        return s1==s2&&fre1==fre2;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_49991368/article/details/113021926