PAT A1071 Speech Patterns (25 分)

这篇博客探讨了C++中处理字符串和字符的方法,包括合法字符判断、大小写转换以及统计出现频率。通过示例代码展示了如何利用getline()和getchar()函数读取输入,并使用map容器存储和查找字符串。同时指出了在处理循环结束条件时可能遇到的问题。
摘要由CSDN通过智能技术生成

题目注意点

  • 可以直接让一个string容器加上字符!!不止可以加字符串
  • 判断循环结束

题解

  • 用getchar()在最后吸收空格时可能出现问题导致第三个点一直不能过。。。
#include <stdio.h>
#include <iostream>
#include <string>
#include <map>
using namespace std;
bool isLegal(char c) {
    if (c >= '0' && c <= '9') return true;
    if (c >= 'a' && c <= 'z') return true;
    if (c >= 'A' && c <= 'Z') return true;
    return false;
}
bool isCap(char c) {
    if (c >= 'A' && c <= 'Z') return true;
    return false;
}
map<string, int> count;
int main() {
    string str, res;
    int max = 0;
    while (1) {
        int index = 0;
        string str2;
        cin >> str;
        for (int i = 0; i < str.length(); i++) {
            if (isLegal(str[i])) {
                if (isCap(str[i])) {
                    str[i] = str[i] + 'a' - 'A';
                }
                str2 += str[i];
                index++;
            }
        }
        if (str2 != "") {
            if (count.find(str2) != count.end()) {
                count[str2]++;
            } else count[str2] = 1;
        }
        if (getchar() == '\n') break;
    }
    for (map<string, int>::iterator it = count.begin(); it != count.end(); it++) {
        if (it->second > max) {
            max = it->second;
            res = it->first;
        }
    }
    cout << res << " " << max << endl;
    return 0;
}
  • 算法笔记:直接用getline(cin, str)读入一整行,然后一个个字符扫描,能组成单词直接判断,不能就直接跳过
#include <stdio.h>
#include <iostream>
#include <string>
#include <map>
using namespace std;
bool isLegal(char c) {
    if (c >= '0' && c <= '9') return true;
    if (c >= 'a' && c <= 'z') return true;
    if (c >= 'A' && c <= 'Z') return true;
    return false;
}
bool isCap(char c) {
    if (c >= 'A' && c <= 'Z') return true;
    return false;
}
map<string, int> count;
int main() {
    string str, res;
    getline(cin, str);
    int i = 0;
    int max = 0;
    while (i < str.size()) {
        string word;
        while (i < str.size() && isLegal(str[i])) {
            if (isCap(str[i])) {
                str[i] += 32;
            }
            word += str[i];
            i++;
        }
        if (word != "") {
            if (count.find(word) == count.end()) count[word] = 1;
            else count[word]++;
        }
        while (i < str.size() && !isLegal(str[i])) {
            i++;
        }
    }
    for (map<string, int>::iterator it = count.begin(); it != count.end(); it++) {
        if (it->second > max) {
            max = it->second;
            res = it->first;
        }
    }
    cout << res << " " << max << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值