
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check if a binary string contains consecutive same or not in C++
Suppose we have a binary string. Our task is to check whether the string has consecutive same characters or not. If there are consecutive same characters, then that is invalid, otherwise valid. Then the string “101010” is valid, but “10111010” is invalid.
To solve this problem, we will traverse from left to right, if two consecutive characters are the same, then return false, otherwise true.
Example
#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"; }
Output
No consecutive same characters
- Related Articles
- Python - Check if a given string is binary string or not
- Check if a binary string has a 0 between 1s or not in C++
- Check if a binary string contains all permutations of length k in C++
- Check If a String Contains All Binary Codes of Size K in C++
- Check if a binary string has two consecutive occurrences of one everywhere in C++
- Check if a string contains a sub-string in C++
- Check if a binary tree is sorted levelwise or not in C++
- Check if SortedDictionary contains the specified key or not in C#
- Check if all the 1s in a binary string are equidistant or not in Python
- Check if a string follows anbn pattern or not in C++
- Check if a Binary Tree contains duplicate subtrees of size 2 or more in C++
- How to check whether a String contains a substring or not?
- Check if a binary tree is sorted level-wise or not in C++
- Program to check if a matrix is Binary matrix or not in C++
- Program to check string contains consecutively descending string or not in Python

Advertisements