您的位置:首页 > 其它

第三天 确定两串乱序同构

2016-07-23 16:44 369 查看
题目描述

给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。

给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。
测试样例:

"This is nowcoder","is This nowcoder"

返回:true

"Here you are","Are you here"

返回:false

看完题目第一反应,要分词啊,这么烦。写了半天,结果只通过31.25%的样例,觉得奇怪就去讨论区看一眼。然后突然发现,XX的被套路了,只要判断数量,不用分词的好吗...
分词版(只通过了一部分样例,所以正确性仍保留意见):
#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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: