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

    你可能感兴趣的文章
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>