【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】
题目描述
给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。
给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。
测试样例:
"This is nowcoder","is This nowcoder"
返回:true
"Here you are","Are you here"
返回:false
思路
使用哈希统计两个字符串中每个字符的个数,最后再来比较,一旦有不相等的,自然就返回false
class Same
{
public:
bool checkSam(string stringA, string stringB)
{
// write code here
int lenA = stringA.length();
int lenB = stringB.length();
if(lenA!=lenB)
return false;
int cntA[256] {0},cntB[256] {0};
for(int i = 0; i<lenA; i++)
cntA[stringA[i]]++;
for(int i = 0; i<lenB; i++)
cntB[stringB[i]]++;
for(int i = 0; i<256; i++)
if(cntA[i]!=cntB[i])
return false;
return true;
}
};