题目描述
给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串中的空格。
给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。
测试样例:
“This is nowcoder”,“is This nowcoder”
返回:true
“Here you are”,“Are you here”
返回:false
思路:应用ASCLL表0到127的字符,设置A、B两个数组,数组下标对应字符的ASCLL码。比较两个数组,如果两个数组相同,那么说明两串重新排列后可相同。
class Same {
public:
bool checkSam(string stringA, string stringB) {
// write code here
int A[128] = { 0 };
int B[128] = { 0 };
int sizA = stringA.size();
int sizB = stringB.size();
for (int i = 0; i < sizA; i++) {
A[stringA[i]]++;
}
for (int j = 0; j < sizB; j++) {
B[stringB[j]]++;
}
for (int k = 0; k <= 127; k++) {
if (A[k] != B[k]) {
return false;
}
}
return true;
}
};