专栏文章

题解:P1308 [NOIP2011 普及组] 统计单词数

P1308题解参与者 20已保存评论 20

文章操作

快速查看文章及其快照的属性,并进行相关操作。

当前评论
20 条
当前快照
1 份
快照标识符
@miqkb42e
此快照首次捕获于
2025/12/04 06:12
3 个月前
此快照最后确认于
2025/12/04 06:12
3 个月前
查看原文

思路

  • 先把两个字符串都再前后添加一个空格,方便匹配完整的单词。
  • 再把所有字符都转成小写,方便操作。
  • 接着用 find 函数去查找,如果开始 pospos 就是 1-1 了,说明整个文章里没有指定单词,直接输出 1-1
  • 否则就要开始统计单词出现的次数了,只要 pospos 不等于 1-1,要一直查找。

注意

  • 由于文章字符串有空格,因此要用 getline
  • 由于需要去掉多余的换行符,所以要用 getchar

代码

CPP
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int main(){
	string c,s;
	cin>>c;
	getchar();
	getline(cin,s);
	c = ' '+c+' ';
	s = ' '+s+' ';
	for(int i=0;c[i];i++){
		c[i] = toupper(c[i]);
	}
	for(int i=0;s[i];i++){
		s[i] = toupper(s[i]);
	} 
	int pos = s.find(c);
	int t = pos;
	if(pos==-1){
		cout<<-1;
		return 0; 
	}
	int cnt = 0;
	while(pos!=-1){
		cnt++;
		pos = s.find(c,pos+1);
	}
	cout<<cnt<<' '<<t<<endl;
	return 0;
}

评论

20 条评论,欢迎与作者交流。

正在加载评论...