概述:
输入一个文本,找出所有不同的单词,按字典序排序,去重后,输出,单词不分大小写。
储备知识:
1、sstring头文件的用法→sstring头文件函数详解
2、cctype头文件的用法→cctype头文件函数详解
题目(提交)链接→UVa-10815
没使用过该网站的同学请猛戳这里→vJudge教程
分析
一、我的思路是:
读到大写字母就转化成小写的,读到小写就存入字符串s,读到非字母就代表这个单词结束了, 将串压入set集合,清空串,循环进行。值得注意的一点是:串的长度为0,也是串,叫做“空串”。也会被压入set。所以压入前要判断一下长度是否为0.为什么会有这种弱智的设定。。。。由于每次都要判断长度,时间复杂度提升,显然不是最优解,代码会贴出来供大家参考。
二、刘先生的思路是:
将大写字母转为小写,将除字母外所有字符转化为空格,最后用stringstream以空格为分界做转化。
我的代码:
#include<iostream>
#include<cctype>
#include<set>
using namespace std;
int main() {
string s;
char ch;
set<string> s1;
while((ch = getchar()) != EOF) {
if(isupper(ch)) ch = tolower(ch);
if(islower(ch)) s += ch;
else {
if(s.length() != 0) {
s1.insert(s); s.clear();
}
}
}
set<string>::iterator it;
for(it = s1.begin(); it != s1.end(); it++) //set中第一个值是ctrl+z后的那个回车。
cout << *it << endl;
return 0;
}
刘先生的代码:
#include<iostream>
#include<string>
#include<set>
#include<sstream>
using namespace std;
set<string> dict;
int main() {
string s, buf;
while(cin >> s) {
for(int i = 0; i < s.length(); i++)
if(isalpha(s[i])) s[i] = tolower(s[i]); else s[i] = ' ';
stringstream ss(s); //将s装入ss
while(ss >> buf) dict.insert(buf);
}
for(set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
cout << *it << '\n';
return 0;
}
收获:
1、字符串长度为0,也是字符串,叫做“空串”
2、z的阿斯克码值等于122
3、巩固了cctype的知识
4、学习了stringstream的新用法