P1308 統計單詞數

很不熟悉字符串處理,我的acm之旅也是跪在了字符串上,這次比賽碰巧字符串的題這麼多。。。

無所謂了,已經退役了,專心考研,刷題只是慣性和興趣,刷刷簡單的題開心開心就好~

這道題是一道水題,但是如果能對c++的自帶函數比較熟悉寫起來會簡單的多,可能效率也會比較好

 

首先要把兩個字符串都轉換成小寫。

其次把特殊情況平凡化。

看題目中單詞的定義,單獨的出現才能算單詞,單獨的出現就是要麼這個單詞是開頭、末尾單詞,要麼是這個單詞前後被空格包裹住。很顯然,被空格包裹住是可能性最多的形式,開頭和末尾都是特殊情況,如果做特判會麻煩不少,於是我可以在字符串的開頭和結尾都加上一個空格,這樣在字符串裏面,搜前後帶空格的單詞就好啦。

 

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
    string str;
    getline(cin, str);
    for(int i=0; i<str.length(); i++)
    {
        if(str[i] >= 'A' && str[i] <= 'Z')
            str[i] = str[i]- 'A' + 'a';
    }
    str = ' ' + str + ' ';
    string str2;
    getline(cin, str2);
    for(int i=0; i<str2.length(); i++)
    {
        if(str2[i] >= 'A' && str2[i] <= 'Z')
            str2[i] = str2[i]- 'A' + 'a';
    }
    str2 = ' ' + str2 + ' ';
    if( str2.find( str) == -1)
    {
        cout<<"-1"<<endl;
    } else{
        int st = str2.find(str, 0);
        int pos = st+1;
        int cnt = 1;
        while( true ) {
            pos = str2.find(str, pos);
            if( pos == -1)break;
            pos = pos + 1;
            cnt++;
        }
        cout<<cnt<<' '<<st<<endl;
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章