查找最大长度奇校验子字符串


简介

在本教程中,我们将开发一种查找最大长度奇校验子字符串的方法。子字符串中的奇校验意味着字符串中“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 次查看

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.