J. Similarity (Easy Version)
time limit per test: 1 second
memory limit per test: 256 megabytes
The easy version and the hard version are different problems, yet it is crucial to retain your solution code once it's accepted, as it might be useful later on.
Many place names bear similarities. Take, for instance, Suzhou and Quzhou. They are considered similar because they share a common substring uzhou. A substring is a contiguous sequence of characters within a string. For example, in the string abcd, bc is a substring of it, but ac is not.
We define the similarity between two strings as the length of their longest common substring. Thus, the similarity between Suzhou and Quzhou is 5, and between Hangzhou and Chengdu it is 2.
Given n place names, your task is to find two names that have the maximum similarity and output the similarity.
Input
The first line contains one integer T (1≤T≤15), indicating the number of test cases.
For each test case, the first line contains an integer n (2≤n≤50), indicating the number of places. Each of the following n lines contains a string s (1≤|s|≤50), indicating the place names. The place names are guaranteed to consist only of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 300.
Output
For each test case, output an integer in a single line representing the maximum similarity.
Example
input
2
2
jiangsu
xiangtan
3
hangzhou
chengdu
wuxi
output
4
2
【思路分析】
模拟。考虑到n,t,|s|都很小,可以直接暴力枚举。将所有字符串两两对比即可。
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <cmath>
#include <algorithm>
#include <climits>
#include <stack>
#include <cstring>
#define i64 long long
using namespace std;
i64 getMaxCnt(string a, string b) {
vector<string> subArr;
for (int i = 0; i < a.length(); ++i) {
for (int j = 1; j <= a.length() - i; ++j) subArr.emplace_back(a.substr(i, j));
}
i64 cnt = 0;
for (const auto &item: subArr) {
if (b.find(item) != string::npos) cnt = max(cnt, (i64) item.length());
}
return cnt;
}
void solve() {
i64 n;
cin >> n;
string s[n];
for (int i = 0; i < n; ++i) cin >> s[i];
i64 cnt = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) cnt = max(cnt, getMaxCnt(s[i], s[j]));
}
cout << cnt << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t = 1;
cin >> t;
while (t--) {
solve();
}
return 0;
}