เราจะเห็นปัญหาที่น่าสนใจอีกอย่างหนึ่ง เราต้องเขียนโค้ดที่ยอมรับสตริงซึ่งมีเกณฑ์ดังต่อไปนี้
- ทุกกลุ่มที่ 1 ติดต่อกัน ต้องมีความยาว 2
- ทุกกลุ่มของ 1 วินาทีที่ต่อเนื่องกันต้องปรากฏหลังจาก 0 วินาทีขึ้นไป
สมมติว่ามีสตริงเช่น 0110 นี่เป็นสตริงที่ถูกต้อง ไม่ว่า 001110, 010 จะไม่ถูกต้องหรือไม่
นี่เป็นแนวทางง่ายๆ เราต้องหาค่า 1 ให้พบ และตรวจสอบว่ามันเป็นส่วนหนึ่งของสตริงย่อย 011 หรือไม่ หากเงื่อนไขล้มเหลว สำหรับสตริงย่อยใดๆ ให้คืนค่าเท็จ มิฉะนั้น จะเป็นจริง
ตัวอย่าง
#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