数组与字符串四(例子、使用(2))

如题:

给定两个字符串,判断它们是否是彼此可置换的。

分析:

1、两个字符串的长度不同,必定不能置换

2、判断是否可以置换,即找到两个字符串的共同点,可以通过某种映射,使得所有置换得到相同的结果。

3、如果两个字符串经过哈希映射后得到的哈希表不同的话,必定不能置换。

代码:

bool isPermutation(string stringA, string stringB){
 //如果两个字符串的长度不等,必定不能互相置换
 if (StringA.length!=StringB.length)
 {
  return false;
 }

 unordered_map<char, int> hashMapA;
 unordered_map<char, int> hashMapB;

 for (int i = 0; i < stringA.length(); i++)
 {
  hashMapA[stringA[i]]++;
  hashMapB[stringB[i]]++;
 }

 //两个哈希表的大小不同,必定不能互相置换
 if (hashMapA.size!=hashMapB.size)
 {
  return false;
 }

 unordered_map<char, int>::iterator it;
 //键、值是否对应
 for (it = hashMap.begin(); it != hashMapA.end(); it++)
 {
  if (it->second!=hashMapB[it->first])
  {
   return false;
  }
 }
 return true;
}

说明:

代码中,it是hashmap的迭代器,it->first指的是哈希表的key,即“键”;it->second指的是哈希表的value,即“值”。

原文地址:https://www.cnblogs.com/revenge/p/6092500.html