Source Code
#include <bits/stdc++.h>
using namespace std;
    
int main (){

  #ifndef ONLINE_JUDGE
    freopen("SuhaibSawalha1","r",stdin);
  #endif

  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  int n;
  string s;
  cin >> n >> s;
  if (s[0] == s[n - 1]) {
    cout << n - 1;
  }
  else {
    bool ok = 0;
    for (int i = 1; i < n; ++i) {
      ok |= s[i - 1] == s[0] && s[i] == s[n - 1];
    }
    cout << (ok ? n - 2 : 0);
  }

  return 0;
}
Copy
Pop Pop SuhaibSawalha1
GNU G++17
1 ms
800 KB
Accepted