查詢最大長度奇校驗子字串


簡介

在本教程中,我們將開發一種查詢最大長度奇校驗子字串的方法。子字串中的奇校驗意味著字串中“1”出現的次數為奇數。在 C++ 中,奇偶校驗定義了位集數,並且是數字中的“1”。奇偶校驗有兩種型別:偶校驗和奇校驗。

當二進位制表示中“1”的總數為奇數時,稱為奇校驗字串。在本教程中,我們將使用 C++ 程式設計概念查詢最大長度奇校驗子字串。

實現 1

String = 101100
Output = 6

在上面的示例中,最大奇校驗子字串的長度為 6,該子字串可以是 011100。在這個子字串中,“1”的總數為 3,這是一個奇數。使其成為奇校驗子字串。

實現 2

String = 1011010
Output = 6

在上面的示例中,從給定字串中最大的長度奇校驗子字串為 6。可能的子字串可以是 011010,因為它包含總共 3 個“1”,使其成為奇校驗子字串。

演算法

  • 建立一個計數器變數 ct 來計算輸入字串中的“1”。

  • 如果 ct 的值為 0,則無法形成奇校驗子字串,因為輸入字串僅包含 0。

  • 如果輸入字串中“1”的總數為奇數,則子字串的長度等於字串的長度。

  • 當 ct 變數的值為偶數時,則可以透過兩種可能性形成子字串。

  • 查詢最長的奇校驗子字串。

  • 列印長度。

示例

我們使用 C++ 實現示例 2,並使用字串類的 length() 函式查詢輸入字串和生成的子字串的長度。

#include <bits/stdc++.h>
using namespace std;
 
// user defined function for calculating the index value of string
int indexOfString(string st, char ch, int j){
   for(; j < st.length(); j++)
      if(st[j] == ch)
      return j;      
      return -1;
}
//finding the lsat index value of the string
int lastIndexOfString(string st,char ch,int j){
   for(; j >= 0; j--)
      if(st[j] == ch)
   return j;
   return -1;
}
 
//user defined function to find the length of the longest odd parity substring
int maxSubstring(string s, int l){

   //variable for counting 1s
   int ct = 0;
   for (int j = 0; j < l; j++)
      if (s[j] == '1')
         ct++;

   //different counter variable conditions
   if (ct == 0)
      return 0;
       
   if (ct % 2 == 1)
      return l;
       
   int firstTime = indexOfString(s,'1',0);
   int secondTime = indexOfString(s,'1', firstTime + 1);

   int lastTime = lastIndexOfString(s,'1',s.length()-1);
   int secondLastTime = lastIndexOfString(s,'1', lastTime - 1);

   return max(lastTime, l - firstTime - 1);
}

// Controller
int main(){
   string s = "1011010";
   int l = s.length();
   cout<<"The maximum length of the odd parity substring is:" <<(maxSubstring(s, l));
}

輸出

The maximum length of the odd parity substring is: 6

結論

在本教程中,我們開發了一種方法來查詢從給定輸入字串中獲取的最長奇校驗子字串的長度。奇校驗子字串的長度是使用計數器變數併為其定義不同的 if 條件來計算的。

我們使用了字串類的 length() 函式,它有助於查詢子字串的長度和輸入字串的索引值。索引值生成子字串。

更新於: 2023年7月31日

86 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告