首页 > 其他 > 详细

hdu 2072 单词数(字符串)

时间:2020-07-04 19:34:28      阅读:32      评论:0      收藏:0      [点我收藏+]

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2072

题意

每行输入由小写字母和空格组成,统计每行中不同的单词数。

题解

题解一

比较简洁的解法,读入每行输入后重定向至字符流 $stringstream$,与 uva10815 相似。

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
    string s;
    while (getline(cin, s) and s != "#") {
        set<string> st;
        stringstream ss(s);
        string t; 
        while (ss >> t)
            st.insert(t);
        cout << st.size() << "\n";
    }
}

题解二

不用 $stringstream$ 的话可以考虑以空格为间隔点截取单词,但需要注意两点:

  • 在每行末尾再加上一个空格,因为可能有的行不以空格结尾
  • 判断截取的起点是否为空格,因为可能有的行以空格开始或有多个空格相邻

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
    string s;
    while (getline(cin, s) and s != "#") {
        set<string> st;
        s.push_back( );
        int pre = 0;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] ==  ) {
                if (s[pre] !=  )
                    st.insert(s.substr(pre, i - pre));
                pre = i + 1;
            }
        }
        cout << st.size() << "\n";
    }
}

 

hdu 2072 单词数(字符串)

原文:https://www.cnblogs.com/Kanoon/p/13236061.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!