题目描述
给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。
给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。
测试样例:
"This is nowcoder","is This nowcoder"
返回:true
"Here you are","Are you here"
返回:false
class Same {
public:
bool checkSam(string stringA, string stringB) {
// write code here
最简单的思路就是对两串进行排序,可以采用快排,
然后进行比较
这里采用桶排序的思路,对每个串里面的字符进行计数,
然后进行比较,若有不同则返回false
用了两个临时数组
/*int strA[256]={0}, strB[256]={0};
int lenA=stringA.length(), lenB=stringB.length();
if(lenA != lenB) return false;
for(int i = 0; i < lenA; ++i)
{
strA[stringA[i]]++;
}
for(int i = 0; i < lenB; ++i)
{
strB[stringB[i]]++;
}
for(int i = 0; i < 256; ++i)
{
if(strA[i] != strB[i]) return false;
}
return true;*/
这里对上面的进行了优化,只用了一个临时数组,
在一个数组进行加的同时,另一个进行减,这样再来
一次for循环,若数组中有不为0的则返回false
int strA[256]={0};
int lenA=stringA.length(), lenB=stringB.length();
if(lenA != lenB) return false;
for(int i = 0; i < lenA; ++i)
{
strA[stringA[i]]++;
strA[stringB[i]]--;
}
for(int i = 0; i < 256; i++)
if(strA[i] != 0)return false;
return true;
}
};
确定两串乱序同构
最新推荐文章于 2020-10-13 20:18:15 发布