You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写可统计单词、回文数及最长回文的C++字符串处理程序求助

代码修正方案

现有代码核心问题

  • 回文计数逻辑错误:当前代码每匹配一对对称字符就对palindrome_count加1,正确逻辑应为所有对称位置字符全部匹配,才计数为1个回文
  • 遗漏末尾单词处理:仅在遇到空格时才判断当前拼接的单词,输入行末尾的单词后无空格,不会进入判断逻辑
  • 多空格场景统计出错:连续多个空格会触发多次判断逻辑,将空字符串识别为有效单词
  • 缺少最长回文记录逻辑:无对应变量存储遍历过程中遇到的最长回文字符串

修复后完整代码

#include <iostream>
#include <string>

// 回文判断工具函数
bool is_palindrome(const std::string& s) {
    int left = 0;
    int right = s.size() - 1;
    while (left < right) {
        if (s[left] != s[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

int main()
{
    std::string current_word = "";
    std::string input_str;
    std::getline(std::cin, input_str);
    int word_count = 0;
    int palindrome_count = 0;
    std::string longest_pal = ""; // 存储最长回文

    for (auto c : input_str) {
        if (c == ' ') {
            // 跳过连续空格,只处理非空单词
            if (!current_word.empty()) {
                word_count++;
                if (is_palindrome(current_word)) {
                    palindrome_count++;
                    // 更新最长回文
                    if (current_word.size() > longest_pal.size()) {
                        longest_pal = current_word;
                    }
                }
                current_word.clear();
            }
        } else {
            current_word += c;
        }
    }

    // 处理最后一个单词
    if (!current_word.empty()) {
        word_count++;
        if (is_palindrome(current_word)) {
            palindrome_count++;
            if (current_word.size() > longest_pal.size()) {
                longest_pal = current_word;
            }
        }
    }

    std::cout << word_count << " words" << std::endl;
    std::cout << palindrome_count << " palindromes" << std::endl;
    if (!longest_pal.empty()) {
        std::cout << "Longest palindrome: " << longest_pal << std::endl;
    } else {
        std::cout << "No palindrome found" << std::endl;
    }
    return 0;
}

核心改动说明

  1. 新增独立的回文判断函数,逻辑清晰且可复用,避免嵌套循环导致的计数错误
  2. 新增longest_pal变量存储最长回文,每次识别到回文时对比长度,实时更新
  3. 优化单词拆分逻辑,跳过连续空格,不会把空字符串识别为有效单词
  4. 循环结束后补充处理最后一个单词,避免遗漏
  5. 单词计数初始值调整为0,只统计有效非空单词,结果更准确

内容的提问来源于stack exchange,提问作者goby gonagle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:27:02