原文地址:http://blog.youkuaiyun.com/v_JULY_v/article/details/6347454。同时也向大家推荐这个文章的博主,技术大牛。
如果两个字符串中所含字符的个数和对应的字符都相等,我们说这两个字符串匹配,比如:abcdea,aabcde。则这两个字符串相等。
特别喜欢这个方法,故转到我空间来,以便记录。
#include <iostream>
#include <string>
using namespace std;
bool Is_Match(const char *strOne,const char *strTwo)
{
int lenOfOne = strlen(strOne);
int lenOfTwo = strlen(strTwo);
// 如果长度不相等则返回false
if (lenOfOne != lenOfTwo)
return false;
// 开辟一个辅助数组并清零
int hash[26] = {0};
// 扫描字符串
for (int i = 0; i < strlen(strOne); i++)
{
// 将字符转换成对应辅助数组中的索引
int index = strOne[i] - 'A';
// 辅助数组中该索引对应元素加1,表示该字符的个数
hash[index]++;
}
// 扫描字符串
for (int j = 0; j < strlen(strTwo); j++)
{
int index = strTwo[j] - 'A';
// 如果辅助数组中该索引对应元素不为0则减1,否则返回false
if (hash[index] != 0)
hash[index]--;
else
return false;
}
return true;
}
int main()
{
string strOne = "ABBA";
string strTwo = "BBAA";
bool flag = Is_Match(strOne.c_str(), strTwo.c_str());
// 如果为true则匹配,否则不匹配
if (flag == true)
cout << "Match" << endl;
else
cout << "No Match" << endl;
return 0;
}