檢查一個二進位制字串是否在 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
廣告