將字串分割成三個不重疊的子字串,並判斷拼接後的字串是否為迴文串的子字串數量
簡介
在本教程中,我們將詳細闡述一種方法,用於從給定的字串 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() 函式返回字串的大小。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP