其他分享
首页 > 其他分享> > P1308 [NOIP2011 普及组] 统计单词数[普及-]

P1308 [NOIP2011 普及组] 统计单词数[普及-]

作者:互联网

https://www.luogu.com.cn/problem/P1308
涉及知识点:模拟,字符串
橙色题
思路?在代码里
#include<bits/stdc++.h>
using namespace std;
string word,sen;
int ans,j,ans1;
int main()
{
    getline(cin,word); //先输入两个字符串 
    getline(cin,sen);
    int lena=word.size(); //求长度 
    int lenb=sen.size();
    for(int i=0; i<lena; i++) word[i]=toupper(word[i]); //转换为大写 
    for(int i=0; i<lenb; i++) sen[i]=toupper(sen[i]);
    for(int i=0; i<=lenb-lena; i++) //sen串-word串的长度 ,枚举每一个字符
    {                               //因为只需在sen串中找到首字母即可,所以为节省时间减去word串的长度 
        for(j=0; j<lenb; j++) //枚举word串的每一个字符,继续判断首字母之后的字母是否相等 
        {
            if(sen[i+j]!=word[j])  break; //两种不可行的情况,直接退出word串的循环,换下一个字符 
            if(i>0&&sen[i-1]!=' ') break;
        }
        //注意:上面j结束循环时多加了一次1 
        if(j==lena&&(sen[i+j]==' '||i+j==lenb)) //如果在上一个循环中没有中途退出且(sen[i+j]也就是该单词后面是空格
        //或单词的结尾正好在sen串边界
        {
            ans++;
            if(ans==1) ans1=i;
        }
    }
    if(ans==0) cout<<"-1";
    else cout<<ans<<" "<<ans1; //输出结果 
    return 0;
}

 

 

标签:lenb,普及,word,NOIP2011,int,单词,ans,sen,P1308
来源: https://www.cnblogs.com/2elaina/p/16450523.html