Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Chef Loves Beautiful Strings (Easy Version)

#include <bits/stdc++.h>
using namespace std;

void solve(string &str) {
    int n = str.length();

    int g = 0;
    char now = str[0];
    for (int i = 0; i < n; i++) {
        if (str[i] == now) {
            continue;
        }
        g++;
        now = str[i];
    }
    // The last group hasn't been accounted for.
    g++;

    long long ans = 1LL * (n - g) * (g - 1);
    ans += 1LL * (g - 2) * (g - 1) / 2;
    cout << ans << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;
    for (int i = 0; i < t; i++) {
        int n;
        cin >> n;
        string str;
        cin >> str;
        solve(str);
    }
    return 0;
}
#include <bits/stdc++.h>
using namespace std;

void solve(string &str) {
    int n = str.length();

    // f[i] = f(str[0...i])
    vector<long long> f(n);

    int g = 1;
    for (int i = 1; i < n; i++) {
        if (str[i] != str[i - 1]) {
            f[i] = f[i - 1] + (i - 1);
            g++;
        } else {
            f[i] = f[i - 1] + (g - 1);
        }
    }

    cout << f[n - 1] << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;
    for (int i = 0; i < t; i++) {
        int n;
        cin >> n;
        string str;
        cin >> str;
        solve(str);
    }
    return 0;
}