地址:http://acm.hdu.edu.cn/showproblem.php?pid=1238
题意:给几组字符串,要你求它们几个最长公共的子串的长度。而且子串可以倒序。
2 3 ABCD BCDFF BRCD 2 rose orchid
2 2
代码:
#include <iostream> #include <algorithm> #include <string> #include <cstdio> #include <cstring> using namespace std; int main() { int t; scanf("%d", &t); while (t--) { char in_0[110]; int n; scanf("%d%s", &n, in_0); int len = strlen(in_0); string in[110]; for (int i = 1; i < n; i++) cin >> in[i]; string a = ""; int ans = 0, cnt = 0; for (int i = 0; i < len; i++){ a += in_0[i]; cnt++; int sign = 1; for (int j = 1; j < n; j++){ string b; reverse(a.begin(), a.end()); // 将a逆序 b = a; reverse(a.begin(), a.end()); //判断a,b字符串是否是in[j]字符串的子串 if (strstr(in[j].c_str(), a.c_str()) == NULL&&strstr(in[j].c_str(), b.c_str()) == NULL){ // string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。 sign = 0; break; } } if (!sign){ a.erase(0, 1); //删除第一个元素 cnt--; } if (ans < cnt) ans = cnt; } printf("%d\n", ans); } return 0; }
注:
1、strstr(*str1, *str2)实现从字符串str1中查找是否有字符串str2,如果有,从str1中的str2位置起,返回str1中str2起始位置的指针,如果没有,返回null。
2、
erase函数的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)
下面给你一个例子:#include < iostream > #include < string > using namespace std; int main () { string str ( " This is an example phrase. " ); string ::iterator it; // 第(1)种用法 str.erase ( 10 , 8 ); cout << str << endl; // "This is an phrase." // 第(2)种用法 it = str.begin() + 9 ; str.erase (it); cout << str << endl; // "This is a phrase." // 第(3)种用法 str.erase (str.begin() + 5 , str.end() - 7 ); cout << str << endl; // "This phrase." return 0 ; }