[ITSA] ITSA 50 Problem 5 - Longest Common Substring

題目

Link: ITSA 50 Problem 5 - Longest Common Substring

Code

C++

#include <string>
#include <iostream>

int main()
{
  std::string line1, line2;
  int length1, length2;
  int max, i, j, k;

  std::ios::sync_with_stdio(false);

  while (std::getline(std::cin, line1))
  {
    std::getline(std::cin, line2);
    length1 = static_cast<int>(line1.length());
    length2 = static_cast<int>(line2.length());
    max = 0;

    for (i = 0; i < length1; ++i)
      for (j = 0; j < length2; ++j)
        for (k = 0; (i + k < length1) && (j + k < length2); ++k)
          if (line1[i + k] == line2[j + k])
          {
            if (k + 1 > max) max = k + 1;
          }
          else break;

    std::cout << max << std::endl;
  }
  return 0;
}

Show Comments