题目链接:FZU 2128 最长子串
写了快一个小时,发现读错题了,我靠。。
记录源串中每个子串出现和结束的下标位置,对结构体按照子串结束位置由小到大排序,最长串肯定是相邻两个子串去头去尾后中间那部分,然后就是枚举找最大值了。
看别人题解发现了strstr用起来很方便。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAX_N = 1000000 + 1000;
const int MAX_M = 100 + 10;
char str[MAX_N];
struct Node
{
int l, r;
};
Node node[MAX_N];
bool cmp(Node a, Node b)
{
return a.r < b.r;
}
int main()
{
//freopen("in.txt", "r", stdin);
int n, cnt, len, _max, temp, pos1, pos2;
char s[MAX_M];
while(gets(str) && strcmp(str, ""))
{
_max = 0;
cnt = 0;
scanf("%d", &n);
getchar();
for(int i = 0; i < n; i++)
{
gets(s);
len = strlen(s);
pos1 = 0;
while(strstr(str + pos1, s) != NULL)
{
pos2 = strstr(str + pos1, s) - str;
node[cnt].l = pos2, node[cnt].r = pos2 + len - 1;
pos1 = node[cnt].r + 1;
cnt++;
}
}
sort(node, node + cnt, cmp);
for(int i = cnt - 1; i > 0; i--)
{
temp = node[i].r - 1 - node[i - 1].l;
_max = max(temp, _max);
}
if(cnt == 0)
printf("%d\n", strlen(str));
else
printf("%d\n", _max);
}
return 0;
}
/**
读错题代码。。
*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
const int MAX_N = 1000000 + 1000;
const int MAX_M = 1000 + 10;
const int MAX_K = 100 + 10;
string strs[MAX_M];
char str[MAX_N];
map <int, vector <string> > _map;
bool cmp(string s1, string s2)
{
return s1.length() > s2.length();
}
int main()
{
int n;
string s;
while(gets(str) && strcmp(str, ""))
{
_map.clear();
scanf("%d", &n);
int _max = 0, temp = 0;
for(int i = 0; i < n; i++)
{
cin >> s;
_map[s[0] - 'a'].push_back(s);
}
map <int, vector <string> > :: iterator it = _map.begin();
for(; it != _map.end(); it++)
sort(it->second.begin(), it->second.end(), cmp);
int len = strlen(str);
int _size1, _size2, m;
vector <string> V;
for(int i = 0; i < len; i++)
{
if(_map.count(str[i] - 'a'))
{
m = i;
V = _map[str[i] - 'a'];
_size1 = V.size();
int j, k;
for(j = 0; j < _size1; j++)
{
_size2 = V[j].size();
for(k = 0; k < _size2; k++)
{
if(str[i] != V[j][k])
break;
else
i++;
}
if(k == _size2)
{
_max = max(temp, _max);
temp = 0;
i--;
break;
}
else
i = m;
}
if(temp != 0)
{
i = m;
temp++;
}
}
else
temp++;
}
_max = max(_max, temp);
printf("%d\n", _max);
}
return 0;
}