计蒜客 11066 A letter from Chensg

本文介绍了一种寻找多个字符串中最长连续子串的算法。通过使用set和map数据结构来存储和查找子串,确保了子串的独特性和普遍性。最终输出所有字符串中都存在的最长公共子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

m个字符串,求最长连续子串

Algorithm

每个串,求每个子串
用set 和 map 存起
set是用了判重的,防止每个串里有重复的
map是全局的
然后就A了
STL大法好

Code

#include <cstdio>
#include <string>
#include <iostream>
#include <map>
#include <set>
using namespace std;
void solve()
{
  map<string, int> mymap;
  int m;
  scanf("%d\n", &m);
  for (int i = 0; i < m; i++)
  {
    set<string> myset;
    string s;
    getline(cin, s);
    for (int j = 0; j < s.size() - 3; j++)
    {
      for (int k = 3; k < s.size() - j; k++)
      {
        string str = s.substr(j, k);
        if (myset.find(str) == myset.end())
        {
          mymap[str]++;
          myset.insert(str);
        }
      }
    }
  }
  string ans;
  for (map<string, int>::iterator it = mymap.begin(); it != mymap.end(); it++)
  {
    if (it->second == m)
    {
      if ((it->first).size() > ans.size())
      {
        ans = it->first;
        continue;
      }
      if ((it->first).size() == ans.size() && (it->first < ans))
      {
        ans = it->first;
      }
    }
  }
  if (ans == "") ans = "No significant commonalities";
  cout << ans << endl;
}
int main()
{
//  freopen("input.txt", "r", stdin);
  int n;
  scanf("%d\n", &n);
  for (int i = 0; i < n; i++)
    solve();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值