
在本教程中,我们将详细阐述一种从给定字符串 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 <bits/stdc++.h>
using namespace std;
// user defined function to check formed substrings are palindrome or not
bool 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 substrings
int 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 code
int 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() 函数返回字符串的大小。
以上就是计算三个不重叠的子字符串,将它们连接起来形成一个回文串的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号