检查一个二进制字符串是否在 C++ 中处处包含某个字符连续出现两次
在此我们将看到另一个有趣的问题。我们必须编写一段代码来接受一个字符串,该字符串满足以下条件。
- 每组连续的 1 必须长度为 2
- 每组连续的 1 必须出现在 1 个或多个 0 之后
假设有一个字符串如 0110,这是一个有效的字符串,而 001110、010 则无效。
此处的做法很简单。我们必须找到 1 的出现情况,并检查它是否是子字符串 011 的一部分。如果条件对任何子字符串不满足,则返回 false,否则返回 true。
示例
#include <bits/stdc++.h>
using namespace std;
bool isValidStr(string str) {
int n = str.length();
int index = find(str.begin(), str.end(), '1') - str.begin();
if (index == 0) //when the string starts with 1, then return false
return false;
while (index <= n - 1) {
if (str[index - 1] != '0') // If 1 doesn't appear after an 0
return false;
if (index + 1 < n && str[index + 1] != '1') // If '1' is not succeeded by another '1'
return false;
if (index + 2 < n && str[index + 2] == '1') // If sub-string is of the type "0111"
return false;
if (index == n - 1) // If str ends with a single 1
return false;
index = find(str.begin() + index + 2, str.end(), '1') - str.begin();
}
return true;
}
int main() {
string str = "011000110110";
if(isValidStr(str)){
cout << str << " is a valid string";
} else {
cout << str << " is NOT a valid string";
}
}输出
011000110110 is a valid string
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP