topcoder题目及我的程序(4)——find reversed string (算法2)

题解

在一个字符串s中找到最长的第一次出现的子串s1,s1满足:s1的反串s2也是s的子串。

算法2:从两头开始循环,找到满足条件的子串便记录其长度和起始位置,且找出当前最长串,循环结束后便找到全局最长子串。

源程序如下: 

/************************************************************************
 * 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
 ***********************************************************************
*/


#include 
< stdio.h >
#include 
< STRING >
#include 
< VECTOR >

using   namespace  std;

class  ReverseSubstring
{
public:
    ReverseSubstring()
{}
    
~ReverseSubstring(){}

    
string findReversed(string input);
}
;

string  ReverseSubstring::findReversed( string  input)
{
    
int len=input.size();

    
int start=0, length=0,t=0;
    
for(int i=0;i<len;i++)
    
{
        
for(int j=len-1;j>=0;j--)
        
{
            t
=0;
            
while((i+t<len) && (j-t>=0&& input.at(i+t)==input.at(j-t))
                t
++;
            
            
if(length<t)
            
{
                start
=i;
                length
=t;
            }

        }

    }


    
return input.substr(start,length);
}


// 显示菜单
void  show_menu()
{
    printf(
"--------------------------------------------- ");
    printf(
"input command to test the program ");
    printf(
"   i or I : input n to test ");
    printf(
"   q or Q : quit ");    
    printf(
"--------------------------------------------- ");
    printf(
"$ input command >");
}


void  main()
{
    
char sstr[50],sinput[10];

    show_menu();

    scanf(
"%s",sinput);
    
while(stricmp(sinput,"q")!=0)
    
{
        
if(stricmp(sinput,"i")==0)
        
{
            printf(
"  please input a string:");
            scanf(
"%s",sstr);

            
string str(sstr);
            ReverseSubstring reverse;
            
string substr=reverse.findReversed(str);

            printf(
"   source  string : %s   longest valid substring: %s ",str.c_str(),substr.c_str());
        }


        
//输入命令
        printf("$ input command >");
        scanf(
"%s",sinput);
    }

}

运行结果如下:

topcoder题目及我的程序(4)——find reversed string (算法2)_第1张图片

 

你可能感兴趣的:(topcoder题目及我的程序(4)——find reversed string (算法2))