檢查二進位制字串是否包含連續相同的字元 (C++)
假設我們有一個二進位制字串。我們的任務是檢查字串是否包含連續相同的字元。如果有連續相同的字元,則無效,否則有效。那麼字串 “101010” 有效,但 “10111010” 無效。
為了解決這個問題,我們將從左向右遍歷,如果兩個連續的字元相同,則返回 false,否則返回 true。
示例
#include <iostream> #include <algorithm> using namespace std; bool isConsecutiveSame(string str){ int len = str.length(); for(int i = 0; i<len - 1; i++){ if(str[i] == str[i + 1]) return false; } return true; } int main() { string str = "101010"; if(isConsecutiveSame(str)) cout << "No consecutive same characters"; else cout << "Consecutive same characters found"; }
輸出
No consecutive same characters
廣告