#1180
Easy Algorithms Count substrings with only one distinct letter
Math String
80.9% acceptance
Mar 31, 2026
363
52
Given a string s, return the number of substrings that have only one distinct letter.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn count_letters(s: String) -> i32 {
let bytes = s.as_bytes();
let mut count = 0i32;
let mut run = 1i32;
for i in 1..bytes.len() {
if bytes[i] == bytes[i - 1] {
run += 1;
} else {
count += run * (run + 1) / 2;
run = 1;
}
}
count += run * (run + 1) / 2;
count
}
}