博客
关于我
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/

    你可能感兴趣的文章
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>