首页  >  文章  >  后端开发  >  找到最长的奇数奇偶校验子串

找到最长的奇数奇偶校验子串

WBOY
WBOY转载
2023-09-07 16:13:02544浏览

找到最长的奇数奇偶校验子串

简介

在本教程中,我们开发了一种查找最大长度奇奇偶校验子字符串的方法。子串中的奇校验意味着 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,并使用 string 类的 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 条件来计算的。

我们使用了 string 类的 length() 函数来帮助查找子字符串的长度和输入字符串的索引值。索引值生成子字符串。

以上是找到最长的奇数奇偶校验子串的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除