如果可以使用以下操作从一个字符串得到另一个字符串,则认为两个字符串 接近 :
- 操作 1:交换任意两个 现有 字符。 - 例如,abcde -> aecdb
 
- 例如,
- 操作 2:将一个 现有 字符的每次出现转换为另一个 现有 字符,并对另一个字符执行相同的操作。 - 例如,aacabb -> bbcbaa(所有a转化为b,而所有的b转换为a)
 
- 例如,
你可以根据需要对任意一个字符串多次使用这两种操作。
给你两个字符串,word1 和 word2 。如果 word1 和 word2 接近 ,就返回 true ;否则,返回 false 。
意思:两个字符串 出现字符种类一样,统计次数后,按次数排序后完全一样。
可以使用int cnt[26]来统计每个字母出现次数,首先判断种类是否一样,然后对cnt排序,判断排序后的次数是否一样。
class Solution {
public:bool closeStrings(string word1, string word2) {int cnt1[26];int cnt2[26];memset(cnt1,0,sizeof(cnt1));memset(cnt2,0,sizeof(cnt2));for(auto c1:word1){cnt1[c1-'a']++;}for(auto c2:word2){cnt2[c2-'a']++;}for(int i=0;i<26;i++){if(cnt1[i]!=0&&cnt2[i]==0)return false;if(cnt1[i]==0&&cnt2[i]!=0)return false;}sort(cnt1,cnt1+26);sort(cnt2,cnt2+26);for(int i=0;i<26;i++){if(cnt1[i]!=cnt2[i])return false;}return true;}
};