当前位置:首页 C++ > 正文

C++求一个字符串中的所有回文字符串并且输出结果(字符串操作)

作者:野牛程序员:2024-06-09 12:17:55 C++阅读 2313
C++求一个字符串中的所有回文字符串并且输出结果(字符串操作)

在C++中,求一个字符串中的所有回文子字符串并输出结果,可以使用双重循环遍历所有可能的子字符串,并检查它们是否为回文。以下是具体的实现方法:

步骤

  1. 遍历字符串的所有子字符串。

  2. 检查每个子字符串是否是回文。

  3. 如果是回文,则将其存储并输出。

代码实现

#include <iostream>
#include <string>
#include <vector>

// 检查一个字符串是否为回文
bool isPalindrome(const std::string& str) {
    int left = 0;
    int right = str.size() - 1;

    while (left < right) {
        if (str[left] != str[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

// 获取所有回文子字符串
std::vector<std::string> getAllPalindromicSubstrings(const std::string& s) {
    std::vector<std::string> palindromes;

    for (int i = 0; i < s.size(); ++i) {
        for (int j = i; j < s.size(); ++j) {
            std::string substring = s.substr(i, j - i + 1);
            if (isPalindrome(substring)) {
                palindromes.push_back(substring);
            }
        }
    }

    return palindromes;
}

int main() {
    std::string input;
    std::cout << "请输入一个字符串: ";
    std::getline(std::cin, input);

    std::vector<std::string> palindromes = getAllPalindromicSubstrings(input);

    std::cout << "所有回文子字符串如下:" << std::endl;
    for (const std::string& palindrome : palindromes) {
        std::cout << palindrome << std::endl;
    }

    return 0;
}

代码解析

  1. isPalindrome函数

    • 用于检查一个字符串是否为回文。

    • 使用两个指针leftright分别从字符串的头和尾向中间移动,比较相应位置的字符。

    • 如果所有对应位置的字符都相同,则该字符串是回文。

  2. getAllPalindromicSubstrings函数

    • 遍历输入字符串的所有可能的子字符串。

    • 使用substr函数提取子字符串,并调用isPalindrome函数检查其是否为回文。

    • 如果是回文,将其加入到结果向量palindromes中。

  3. main函数

    • 获取用户输入的字符串。

    • 调用getAllPalindromicSubstrings函数获取所有回文子字符串。

    • 输出结果。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
  • C++
  • 最新推荐

    热门点击