第三天 確定兩串亂序同構

題目描述
給定兩個字符串,請編寫程序,確定其中一個字符串的字符重新排列後,能否變成另一個字符串。這裏規定大小寫爲不同字符,且考慮字符串重點空格。
給定一個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;
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章