首頁  >  文章  >  後端開發  >  計算三個不重疊的子字串,將它們連接起來形成一個回文串

計算三個不重疊的子字串,將它們連接起來形成一個回文串

王林
王林轉載
2023-09-07 18:25:021210瀏覽

計算三個不重疊的子字串,將它們連接起來形成一個回文串

簡介

在本教程中,我們將詳細闡述一種從給定字串 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中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除