1. 程式人生 > >C++筆試題 最長公共子串

C++筆試題 最長公共子串

最長公共子串

描述

給出兩個字串,找到最長公共子串,並返回其長度。

輸入描述

輸入兩個任意長度的英文字串

輸出描述

返回公共字串的長度

樣例輸入 1

A=“ABCD”,B=“CBCE”

樣例輸出 1

2

#include <iostream>
#include <string>   // swap()

using namespace std;

class CambrianTest
{
public:
    int getLengthOfLargestCommonSubStr(const string& str1,
const string& str2); }; int CambrianTest::getLengthOfLargestCommonSubStr(const string& str1, const string& str2) { string longerStr(str1); string shorterStr(str2); if (shorterStr.size() > longerStr.size()) { swap(shorterStr, longerStr); } if (longerStr.
find(shorterStr) != string::npos) { return shorterStr.size(); } int size = shorterStr.size(); string largestSubStr = ""; string subStr; for (int i = 0; i < size; i++) // i is start position of sub-str of shorterStr { for (int j = i+1; j < size; j++) // j is end position of sub-str of shorterStr
{ subStr.assign(shorterStr.begin() + i, shorterStr.begin() + j); if (longerStr.find(subStr) != string::npos) { if (largestSubStr.size() < subStr.size()) { largestSubStr = subStr; } } } } #ifdef UNIT_TEST cout << largestSubStr << endl; #endif return largestSubStr.size(); } int main() { string A, B; cin >> A >> B; CambrianTest ct; cout << ct.getLengthOfLargestCommonSubStr(A, B) << endl; return 0; }