
简介
在本教程中,我们将详细阐述一种从给定字符串 s 中查找三个不重叠子字符串的方法,并且当所有子字符串组合在一起时,它们形成一个回文。为了解决此任务,我们使用 C++ 编程语言的字符串类功能。
字符串中的回文表示该字符串在向前和向后方向上读起来都相同。回文字符串示例是 Madam。
假设有一个字符串“s”,子字符串是a、b、c。当您组合 a、b 和 c 时,它们形成回文字符串。这是一个理解问题逻辑的例子。
语句解释
String s = “abbacab” Acceptable substrings of length 3 are: “abb”, “bac”, and “bba”.
当我们连接所有三个子字符串时,生成的字符串是回文字符串,该字符串是 abbbacbba。
语法
size()函数属于字符串类,用于获取输入字符串的大小及其字符长度。
string_name,size();
算法
获取输入字符串。
初始化一个计数器变量,用于跟踪回文子字符串的数量。
使用 3 个嵌套的 for 循环生成 3 个可能的已定义长度的子字符串。
第一个内部循环从 0 初始化到字符串长度 – 3。
第二个内部循环从第一个内部循环 + 1 初始化为字符串长度 – 2。
外循环从第二个循环 + 1 初始化为字符串长度 – 1。
找到所有子字符串后,将它们连接起来。
检查是否存在子串回文,如果存在,则增加计数器变量值。
打印计数器变量值。
示例
为了使用 C++ 实现上述算法,我们使用输入字符串并生成子字符串的所有可能组合,并仅考虑那些回文子字符串。如果这样的子串是可能的,计数器变量将增加。打印计数器变量的结果。
#include using namespace std; // user defined function to check formed substrings are palindrome or notbool isStringPalin(int a, int b, int c, int d, int x, int y, string st){ int begin = a, stop = y; while (begin < stop) { if (st[begin] != st[stop]) return false; begin++; if (begin == b + 1) begin = c; stop--; if (stop == x - 1) stop = d; } return true;} // User defined function to count the number of useful substringsint countSubString(string st){ //Counting variable to count and return the number of substrings int ct = 0; int l = st.size(); //It is to select the first substring for (int a = 0; a < l - 2; a++) { for (int b = a; b < l - 2; b++){ // This loop selects the second useful substring for (int c = b + 1; c < l - 1; c++) { for (int d = c; d < l - 1; d++) { // this for loop will select the third substring for (int x = d + 1; x < l; x++) { for (int y = x; y < l; y++) { // If condition to check the selected substrings are forming palindrome or not if (isStringPalin(a, b, c, d, x, y, st)) { ct++; } } } } } } } // returning the count variable that stores the number of useful substrings return ct;} // Controlling codeint main(){ string st = "abcab"; cout << "The possible number of substrings are: "<< countSubString(st); return 0;}
输出
The possible number of substrings are: 4
结论
我们开发了一种方法来查找形成回文的有效子字符串。为了实现该解决方案,我们使用了 C++ 循环和 if 条件。为了使用 C++ 实现示例之一,我们使用了 size() 函数和嵌套循环。嵌套循环有助于查找不同长度的子字符串,并且 size() 函数返回字符串的大小。
以上就是计算三个不重叠的子字符串,将它们连接起来形成一个回文串的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444583.html
微信扫一扫
支付宝扫一扫