题目链接: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"; } }
原文:https://www.cnblogs.com/Kanoon/p/13236061.html