HDU 1238 Substrings

地址:http://acm.hdu.edu.cn/showproblem.php?pid=1238

题意:给几组字符串,要你求它们几个最长公共的子串的长度。而且子串可以倒序。

Sample Input
  
  
2 3 ABCD BCDFF BRCD 2 rose orchid
 

Sample Output
  
  
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 ; }
复制代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值