检查相同的字母是否在字符串中连续出现 3 次

Checking if same letter appears 3 times consecutively in string

本文关键字:连续 字符串 是否 检查      更新时间:2023-10-16
// a is some string;
b=a.length; 
for(int i=1; i<b; i++)
{
    if(a[i-1]==a[i]==a[i+1])
        {
            cout <<a[i]<<endl;
//more to add
        }
}

想要检查是否出现相同的 3 个或更多字母 - 这里有什么问题?

您的具体问题是:

a[i-1]==a[i]==a[i+1]

评估为

(a[i-1] == a[i]) == a[i+1]

要么是

true == a[i+1]
false == a[i+1]

这两种可能都不是你想要的。此外,当i == a.size()时,a[i+1]会读出字符串的末尾,这是未定义的行为。

此外,您的标题声称您要检查一个字母是否出现超过 2 次,但您的代码即使固定,也会检查它是否连续出现 3 次。如果您确实要检查 3 次出现,只需使用 std::count

for (int i = 0; i < a.size(); ++i) {
    if (std::count(a.begin(), a.end(), a[i]) >= 3) {
        // success!
    }
}

检查字符串中 N 个连续字符的另一种实现(线性时间复杂度(,

const std::size_t N = 3;
std::string text { "this is a string" };
std::size_t index = 0;
std::size_t num_same_char = 1;
while (index + N - num_same_char < text.size()) {
  if (num_same_char == N) {
    // found at index
    break;
  }
  if (text[index] == text[index + num_same_char]) {
    num_same_char++;
  }
  else {
    num_same_char = 1;
    index += num_same_char;
  }
}
// a is some string;
b=a.length; 
for(int i=1; i<b-1; i++) **//Iterate till b-1 not b**
{
    if(a[i-1]==a[i] && a[i]==a[i+1])
        {
            cout <<a[i]<<endl;
            //more to add
        }
}

希望这有帮助。