题意解析

在一个句子中,查找一个单词的出现次数和首次出现位置。

思路解析

思路一

运用while(cin>>)分离句子,逐一对比。 但由于此题有多个空格,因此会WA

#include<bits/stdc++.h>
using namespace std;
string x,s;
long long cnt,f,d,e;
int main(){
	freopen("cal.in","r",stdin);
	freopen("cal.out","w",stdout);
	cin>>x;
	for(int i=0;i<x.size();i++)if('A'<=x[i] and x[i]<='Z')x[i]=x[i]-'A'+'a';
	while(cin>>s){
		for(int i=0;i<s.size();i++)if('A'<=s[i] and s[i]<='Z')s[i]=s[i]-'A'+'a';
		if(x==s){
			cnt++;
			if(e==0)f=d,e=1;
		}
		d=d+s.size()+1;
	}
for(int i=0;i<s.size();i++)if('A'<=s[i] and s[i]<='Z')s[i]=s[i]-'A'+'a';
		if(x==s){
			cnt++;
			if(e==0)f=d,e=1;
		}
	if(cnt==0)cout<<-1;
	else cout<<cnt<<" "<<f;
}

注意末尾空格。

思路二

运用c++内置find查找

#include<bits/stdc++.h>
using namespace std;
string x,s;
long long cnt,f,d;
int main(){
	//freopen("cal.in","r",stdin);
	//freopen("cal.out","w",stdout);
	getline(cin,x);
	for(int i=0;i<x.size();i++)if('A'<=x[i] and x[i]<='Z')x[i]=x[i]-'A'+'a';
	getline(cin,s);
	for(int i=0;i<s.size();i++)if('A'<=s[i] and s[i]<='Z')s[i]=s[i]-'A'+'a';
	x=" "+x+" ";
	s=" "+s+" ";
	d=int(s.find(x)); 
	f=d;
	while(d!=-1){
		cnt++;
		d=int(s.find(x,d+1));
	}
	if(f==-1)cout<<-1; 
	else cout<<cnt<<" "<<f;
}

0 条评论

目前还没有评论...