Count Substrings with Only One Distinct Letter

easy string counting two pointers

Problem

Given a string s, return the number of substrings that have only one distinct letter. A substring is a contiguous slice of s, and we want those where every character is identical.

Inputs = "aaaba"
Output8
Runs are "aaa", "b", "a". A run of length n yields n·(n+1)/2 substrings: 3·4/2 = 6, plus 1, plus 1 = 8.

def count_letters(s):
    total = 0
    run = 0
    for i, ch in enumerate(s):
        if i > 0 and ch == s[i - 1]:
            run += 1
        else:
            run = 1
        total += run
    return total
function countLetters(s) {
  let total = 0;
  let run = 0;
  for (let i = 0; i < s.length; i++) {
    if (i > 0 && s[i] === s[i - 1]) {
      run += 1;
    } else {
      run = 1;
    }
    total += run;
  }
  return total;
}
class Solution {
    public int countLetters(String s) {
        int total = 0, run = 0;
        for (int i = 0; i < s.length(); i++) {
            if (i > 0 && s.charAt(i) == s.charAt(i - 1)) {
                run += 1;
            } else {
                run = 1;
            }
            total += run;
        }
        return total;
    }
}
int countLetters(string s) {
    int total = 0, run = 0;
    for (int i = 0; i < (int)s.size(); i++) {
        if (i > 0 && s[i] == s[i - 1]) {
            run += 1;
        } else {
            run = 1;
        }
        total += run;
    }
    return total;
}
Time: O(n) Space: O(1)