字符串反转(reverse函数)

猜一下下面函数的功能:
char *strrev(char *str)

{

      char *p1, *p2;

 

      if (! str || ! *str)

            return str;

      for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)

      {

            *p1 ^= *p2;

            *p2 ^= *p1;

            *p1 ^= *p2;

      }

      return str;

}
有一个函数叫reverse函数,头文件为#include
//reverse()的实现

#include 
#include 

char* reverse(char* s)
{
    int i,j;
    for (i=0,j=strlen(s)-1;
        i

用法:

例题:

Substring

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 1
描述

You are given a string input. You are to find the longest substring of input such that the reversal of the substring is also a substring of input. In case of a tie, return the string that occurs earliest in input. 

Note well: The substring and its reversal may overlap partially or completely. The entire original string is itself a valid substring . The best we can do is find a one character substring, so we implement the tie-breaker rule of taking the earliest one first.

输入
The first line of input gives a single integer, 1 ≤ N ≤ 10, the number of test cases. Then follow, for each test case, a line containing between 1 and 50 characters, inclusive. Each character of input will be an uppercase letter ('A'-'Z').
输出
Output for each test case the longest substring of input such that the reversal of the substring is also a substring of input
样例输入
3                   
ABCABA
XYZ
XCVCX
样例输出
ABA
X
XCVCX
来源
第四届河南省程序设计大赛

代码:

#include
#include
#include
#include
#include
#include
#include//注意不是string.h
using namespace std;
int main()
{
int n;
scanf("%d",&n);
string s1,s2,s3;//字符串对象,其实属于一个类
while(n--)
{
cin>>s1;
s2=s1;
int max=0;//用于记录最小子字符串的范围
reverse(s2.begin(),s2.end());//将s2从尾到头反转
int len=s1.size();//返回字符串s1的长度
for(int i=0; i {//i,j用来控制接下来s1生成子字符串的范围
for(int j=1; j<=len-i; j++)
{//查找s1的子字符串,如果没有匹配就返回特殊值string::npos,匹配了就返回size_type类型的pos
string::size_type pos=s2.find(s1.substr(i,j));
if(pos!=string::npos)//如果已匹配
{
if(max {
max=j;
s3=s1.substr(i,j);//把刚刚s1生成的子字符串给s3
}
}
}
}
cout< }
return 0;
}

你可能感兴趣的:(ACM:字符串处理)