Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตรวจสอบ Binary String มี Consecutive Same Characters ใน C++

สมมติมี Binary String ต้องตรวจสอบว่ามี Consecutive Same Characters หรือไม่ ถ้ามี = Invalid มิฉะนั้น Valid ตัวอย่าง "101010" Valid แต่ "10111010" Invalid

Traverse ซ้ายไปขวา ถ้า 2 Consecutive Characters เหมือนกัน คืนค่า false มิฉะนั้น true

ตัวอย่างโค้ด C++

#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