Luo Gu -P1308 statistics the number of words
Link to the original question: https://www.luogu.com.cn/problem/P1308
- Title Description
- Input Format
- Output Format
- Sample input and output
- Description / Tips
- C ++ code
- answer
Title Description
General text editors have to find the word function, which can quickly locate a particular word in the article, some can count the number of times a particular word appears in the article.
Now, you are programming this function, specific requirements are: Given a word, you output the number of times it appears in a given article and the position of the first occurrence. Note: the same as the match word, case-insensitive, but requires an exact match, i.e. must be given with an independent word in the word article insensitive case (see sample 1), if the given word only part of the article is not a word match (see sample 2).
Input Format
Total 2 line.
A behavior of the first string, which contains only letters, represents a given word;
Conduct a second string, which may only contain letters and spaces representing a given article.
Output Format
Line, if found in the article given word is output two integers, separated by a space between two integers, are the location and the number of words that appear in the article first appeared (ie, the first in the article when occurrence, the first letter of the word in the article location, location, starting from 0); If the word does not appear in the article, is a direct output integer -1.
Sample input and output
Input # 1
To
to be or not to be is a question
Output # 1
2 0
Input # 2
to
Did the Ottoman Empire lose its power at that time
Output # 2
-1
Description / Tips
data range
1≤ word length ≤10.
1≤ article length ≤1,000,000.
noip2011 popularity of Group 2 title
C ++ code
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string a,b;
int i,j,lena,lenb,idx,count=0;
getline(cin,a);
getline(cin,b);
lena=a.size();
lenb=b.size();
for(i=0;i<lena;++i)
a[i]=tolower(a[i]);
for(i=0;i<lenb;++i)
b[i]=tolower(b[i]);
for(i=0;i<lenb;++i)
{
for(j=0;j<lena;++j)
if(a[j]!=b[i+j]||(i>0&&b[i-1]!=' '))
break;
if(j==lena&&(b[i+j]==' '||i+j==lenb)) {
++count;
if(count==1)
idx=i;
}
}
if(count)
cout<<count<<' '<<idx<<endl;
else
cout<<-1<<endl;
return 0;
}
answer
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
string sent,word;
int lens,lenw,t,pos;
int main()
{
getline(cin,word);
getline(cin,sent); //字符串含有空格输入,不可以用cin,否则to me只能读到to
lenw=word.size();
lens=sent.size();
for(int i=0;i<lenw;i++)
word[i]=toupper(word[i]); //转成大写
for(int i=0;i<lens;i++)
sent[i]=toupper(sent[i]);
t=0;
for(int i=0;i<=lens-lenw;i++)
{
int j;
for(j=0;j<lenw;++j)
{
if(sent[j+i]!=word[j]) break;
if(i>0&&sent[i-1]!=' ') break; //不是单词开头就结束
}
if(j==lenw&&(sent[j+i]==' '||j+i==lens)) //单词长度匹配,后面是空格或者句末
{
t++;
if(t==1) pos=i;
}
}
if(t==0)cout<<-1;
else cout<<t<<" "<<pos;
return 0;
}