题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

#include <iostream>
using namespace std;

class LongestCommonSubstr {
  private:
    string a, b;

  public:
    //构造函数
    LongestCommonSubstr(const string a, const string b);

    //析构函数
    ~LongestCommonSubstr();

    //最长公共子串
    const string search(void)const;

    //较短字符串的长度(子串最大可能长度)
    const int lengthOfShorterString(void)const;
};

LongestCommonSubstr::LongestCommonSubstr(const string a, const string b) {
    this->a = a;
    this->b = b;
    return;
}

LongestCommonSubstr::~LongestCommonSubstr() {
}

const string LongestCommonSubstr::search(void) const {
    //区分出较短字串和较长字串
    int len = this->lengthOfShorterString();
    string shorter, longer;
    if (this->a.size() == len) {
        shorter = this->a;
        longer = this->b;
    } else {
        longer = this->a;
        shorter = this->b;
    }

    //从子串的最长可能长度开始,从较短字符串字符串的前部开始,搜寻公共子串
    for (; len > 0; len--)
        for (int i = 0; i <= shorter.size() - len; i++) {
            string sub = shorter.substr(i, len);
            for (int j = 0; j <= longer.size() - len; j++)
                if (sub == longer.substr(j, len))
                    return sub;
        }
    return string();
}

const int LongestCommonSubstr::lengthOfShorterString(void) const {
    int a = this->a.size();
    int b = this->b.size();
    return a < b ? a : b;
}

int main() {
    string a, b;
    while (cin >> a >> b) { // 注意 while 处理多个 case
        cout << LongestCommonSubstr(a, b).search() << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

Twilight_mu:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务