1029-短语搜索

描述

常见文本编辑器的一个功能是搜索,打开一段英文文字,根据一个给定的英文短语,可以搜索得到这个短语在文章中的位置,短语有可能重复出现。现请求出给定的短语在一段文字中出现的最后一个位置。文字中单词从1开始编号,所求的位置为短语第1个单词在这段文字中对应单词的编号。

输入

多行,每行以 # 为结束,第1行为一段英文文字(单词数、数字不多于500),其余行是待搜索的英文短语(单词数不多于10)。这里英文文字、英文短语只包含英文单词,这些单词以空格分隔。

输出

多行,每一行对应输入中给定的短语在文字中出现的最后一个位置,搜索不到时输出-1

样例输入

STOCKHOLM April 21 PRNewswire FirstCall Students from St Petersburg State University of IT Mechanics and Optics are crowned the 2009 ACM International Collegiate Programming Contest World Champions in the Stockholm Concert Hall where the Nobel Prizes are presented every year Sponsored by IBM the competition took place today at KTH the Royal Institute of Technology #

STOCKHOLM #

St Petersburg State University of IT Mechanics and Optics #

World Champions #

the #

NUPT #

样例输出

1

8

26

51

-1

#include<iostream>
using namespace std;
int main()
{
    int j,len,len2,flag2;
    bool flag;
    int i=0;
    char str[501][11];
    char cu[501][11];
    while(scanf("%s",&str[i]))
    {
        if(strcmp(str[i],"#")==0)
            break;
        else
            i++;
    }
    len=i;
    i=0;
    for(i=0;scanf("%s",&cu[i])!=EOF;i++)
    {
        if(strcmp(cu[i],"#")==0)
        {
            len2=i;
            flag2=-1;
            for(i=0;i<len;i++)
            {
                flag=true;
                for(j=0;j<len2;j++)
                {
                    if(strcmp(str[i+j],cu[j])!=0)
                    {
                        flag=false;
                        break;
                    }
                }
                if(flag)
                {
                    flag2=i+1;
                }
            }
            cout<<flag2<<endl;
            i=-1;
        }
    }
    return 0;
} 

  

原文地址:https://www.cnblogs.com/Rosanna/p/3436601.html