例题5-3 UVA10815 Andy's First Dictionary(17行AC代码)

紫书刷题进行中,题解系列【GitHub|CSDN

例题5-3 UVA10815 Andy’s First Dictionary(17行AC代码)

思路分析

给定若干行字符串,按字典序输出不重复的单词

  • 字典序排列和去重:定义set<string> dict; 存储词典,自动去重且按字典序排列
  • 可用getline读入每一行,将其字母均转为小写,非字母转为空格,拼接文本
  • 可用stringstream分割空格间隔的字符串

注意点

  • 拼接每一行时注意加上空格,避免首尾直接相接,照成错误单词

AC代码(C++11,set)

#include<bits/stdc++.h>
using namespace std;
string text, s;
set<string> dict; // 词典
int main() {
    while (getline(cin, s)) {
        for (auto& ch : s) {
            if (isalpha(ch)) ch = tolower(ch); // 替换小写
            else ch = ' '; // 替换空格 
        }
        text += " "+s; // 拼接文本,注意空格,避免两行尾首直接相连
    }
    stringstream input(text); // 按空格分割
    while (input >>s) dict.insert(s); // 插入去重
    for (auto p : dict) cout <<p <<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值