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

    你可能感兴趣的文章
    oracle 创建双向备份,Materialized View 物化视图实现 Oracle 表双向同步
    查看>>
    oracle 创建字段自增长——两种实现方式汇总
    查看>>
    Oracle 升级10.2.0.5.4 OPatch 报错Patch 12419392 Optional component(s) missing 解决方法
    查看>>
    oracle 去重
    查看>>
    oracle 可传输的表空间:rman
    查看>>
    Oracle 启动监听命令
    查看>>
    Oracle 启动阶段 OPEN
    查看>>
    Oracle 在Drop表时的Cascade Constraints
    查看>>
    Oracle 在Sqlplus 执行sql脚本文件。
    查看>>
    Oracle 如何处理CLOB字段
    查看>>
    oracle 学习
    查看>>
    oracle 定义双重循环例子
    查看>>
    ORACLE 客户端工具连接oracle 12504
    查看>>
    Oracle 客户端连接时报ORA-01019错误总结
    查看>>
    oracle 导出sql数据库表结构,使用sql developer 导出Oracle数据库中的表结构
    查看>>
    oracle 嵌套表 例子,Oracle之嵌套表(了解)
    查看>>
    Oracle 常用命令
    查看>>
    Oracle 常用的V$视图脚本(二)
    查看>>
    Oracle 并行原理与示例总结
    查看>>
    oracle 并集 时间_Oracle集合运算符 交集 并集 差集
    查看>>