检查二进制字符串是否包含连续相同的字符 (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

更新于:21-10-2019

浏览量:253

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.