短语搜索

来源:互联网 发布:光之教堂数据 编辑:程序博客网 时间:2024/04/19 23:18

题目链接为:http://acm.njupt.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=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

其实就是确定单词出现的位置后,再判断是属于第几个单词即可。(PS:数单词时玩了个巧,单词数等于空格数+1;这是对于单词都由单空格隔开的情况,如果对于单词可由多个空格隔开的话,那么就错了;不过估计不会出现这种情况,所以懒得判断)

#include<iostream>using namespace std;int indexOf(string input,string str){    int i=0;    bool find=true;    int result=-1;    while(i<input.length()){                                   int j=0;       int original=i;       if(input[i]==str[j])       {           for(j=1;j<str.length();j++)           {                 i++;                 if(i>=input.length()||input[i]!=str[j])                 {                     find=false;                     break;                 }           }        }        else       {           find=false;        }       if(find){                           result=original;              }         find=true;       i=original;       i++;           }    return result;}int main(){       string input,str;   getline(cin,input);   input=input.substr(0,input.length()-2);   while(getline(cin,str)){          str=str.substr(0,str.length()-2);              int len=-1;          len=indexOf(input,str);       int num=0;       //判断是属于第几个单词       for(int i=0;i<=len;i++)       {           if(input[i]==' ')           {               num++;            }       }                    if(len==-1)       {           num=-1;        }           else       {           num++;        }       cout<<num<<endl;   }      system("pause");   return 0;    } 
原创粉丝点击