第三天 确定两串乱序同构

题目描述
给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。
给定一个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;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值