字符串反转(reverse函数)

来源:互联网 发布:模具分析软件 编辑:程序博客网 时间:2024/06/02 09:38
猜一下下面函数的功能:
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<string>
//reverse()的实现#include <stdio.h>#include <string.h>char* reverse(char* s){    int i,j;    for (i=0,j=strlen(s)-1;        i<j; ++i,--j)    {        s[i] = s[i]^s[j];        s[j] = s[i]^s[j];        s[i] = s[i]^s[j];    }    return s;}char* reverse2(char* s){    char* start = s;    char* end = s+strlen(s)-1;    while (start<end)    {        *start = *start^*end;        *end = *start^*end;        *start = *start^*end;        start++;        end--;    }    return s;}int main(){    char str[]="abcdefghijklmnopqrstuvwxyz";    printf("%s\n", str);    printf("%s\n", reverse(str));    printf("%s\n", reverse2(str));    return 0;}

用法:

例题:

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                   ABCABAXYZXCVCX
样例输出
ABAXXCVCX
来源
第四届河南省程序设计大赛

代码:

#include<stdio.h>
#include<math.h>
#include<stdio.h>
#include<stack>
#include<iostream>
#include<algorithm>
#include<string>//注意不是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<len; 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<j)//确保s3接收的是最短子字符串
{
max=j;
s3=s1.substr(i,j);//把刚刚s1生成的子字符串给s3
}
}
}
}
cout<<s3<<endl;
}
return 0;
}

1 0