在这里,我们将看到另一个有趣的问题。我们必须编写一个接受字符串的代码,该代码具有以下条件。
每组连续的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