C++ 寻找最长奇偶校验子串
引言
在本教程中,我们将开发一种寻找最长奇偶校验子串的方法。奇偶校验意味着一个字符串中数字 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()函数来帮助找到子串的长度以及输入字符串的索引值。索引值生成子串。