1. 程式人生 > >字串反轉(reverse函式)

字串反轉(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<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                   
ABCABA
XYZ
XCVCX
樣例輸出
ABA
X
XCVCX
來源

程式碼:

#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;
}