题目链接: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() << " "; } }
题解二
不用 $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() << " "; } }