題目描述
給定兩個字符串,請編寫程序,確定其中一個字符串的字符重新排列後,能否變成另一個字符串。這裏規定大小寫爲不同字符,且考慮字符串重點空格。
給定一個string stringA和一個string stringB,請返回一個bool,代表兩串是否重新排列後可相同。保證兩串的長度都小於等於5000。
測試樣例:
"This is nowcoder","is This nowcoder"返回:true
"Here you are","Are you here"
返回:false
#include <iostream>
//#include <vector>
#include <string>
using namespace std;
bool checkString(string a, string b, int len)
{
int i = 0;
while(i + len -1 < b.size())
{
string temp(b, i, len);
if (temp == a)
return true;
else
i++;
}
return false;
}
bool checkSame(string A, string B)
{
string::iterator a = A.begin(), b = a;
bool x;
// 最後一個沒考慮
while(b != A.end())
{
if (*b == ' ' && b != a)
{
string temp(a,b);
int len = b - a;
a = b + 1;
while (*a == ' ')
a++;
b = a;
x = checkString(temp, B, len);
if (!x)
return false;
}
else
b++;
}
if (b == A.end())
{
string temp(a,b);
int len = b - a;
x = checkString(temp, B, len);
if (!x)
return false;
}
return true;
}
int main ()
{
string A("This is nowcoder"), B("is This nowcoder");
//string A("Here you are"), B("Are you here");
cout << checkSame(A, B) << endl;
return 0;
}
另外附上哭笑不得的計數君:
class Same {
public:
bool checkSam(string stringA, string stringB) {
// write code here
int sizA = stringA.size();
int sizB = stringB.size();
if(sizA != sizB) return false;
char A[256] = {0};
char B[256] = {0};
for(int i = 0; i < sizA; i++){
A[stringA[i]]++;
B[stringB[i]]++;
}
for(int i = 0; i < 256; i++){
if(A[i] != B[i]) return false;
}
return true;
}
};
class Same {
public:
bool checkSam(string stringA, string stringB) {
sort(stringA.begin(),stringA.end());
sort(stringB.begin(),stringB.end());
return stringA.compare(stringB)==0;
}
};