博客
关于我
9.统计回文
阅读量:122 次
发布时间:2019-02-27

本文共 1195 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要找到将字符串B插入字符串A的所有可能位置,使得插入后的字符串是一个回文串。回文串是指正读和反读都一样的字符串。

方法思路

  • 回文判断函数:首先,我们需要一个函数来判断一个字符串是否是回文串。这个函数从字符串的两端同时开始比较字符,直到中间位置。
  • 遍历插入位置:对于每个可能的位置,将字符串B插入到字符串A的位置,然后检查插入后的字符串是否是回文。
  • 处理特殊情况:如果字符串B为空,那么插入后的字符串就是原来的字符串A。如果A是回文,那么方法数是A的长度加1,否则为0。
  • 解决代码

    #include 
    #include
    using namespace std;bool IsCircle(const string &s) { int begin = 0, end = s.size() - 1; while (begin < end) { if (s[begin] != s[end]) { return false; } begin++; end--; } return true;}int main() { string str1, str2; getline(cin, str1); getline(cin, str2); if (str2.empty()) { if (IsCircle(str1)) { cout << str1.size() + 1 << endl; } else { cout << 0 << endl; } return 0; } int count = 0; for (int i = 0; i <= str1.size(); i++) { string temp = str1; temp.insert(i, str2); if (IsCircle(temp)) { count++; } } cout << count << endl; return 0;}

    代码解释

  • IsCircle函数:这个函数检查字符串是否是回文。从字符串两端开始,逐步向中间比较字符,直到两端相遇。
  • 读取输入:从标准输入读取字符串A和B。
  • 处理空字符串B:如果B为空,检查A是否是回文,如果是,输出A的长度加1,否则输出0。
  • 遍历插入位置:对于每个可能的位置插入B,生成新字符串并检查是否是回文,统计符合条件的情况。
  • 输出结果:输出满足条件的插入方法数。
  • 转载地址:http://jpbb.baihongyu.com/

    你可能感兴趣的文章
    npm发布包--所遇到的问题
    查看>>
    npm发布自己的组件UI包(详细步骤,图文并茂)
    查看>>
    npm和yarn清理缓存命令
    查看>>
    npm和yarn的使用对比
    查看>>
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>