LeetCode: Count Number Of Homogenous Substrings Solution

Approach

Accumulated count for contiguous substring of the same characters

1"a" -> 1 (1)
2"aa" -> 3 (1 + 2)
3"aaa" -> 6 (1 + 2 + 3)

Implementation

1/**
2 * @param {string} s
3 * @return {number}
4 */
5var countHomogenous = function (s) {
6 let res = 0,
7 prev = "",
8 acc
9 for (const c of s) {
10 acc = c === prev ? acc + 1 : 1
11 prev = c
12 res += acc
13 }
14 return res % (1e9 + 7)
15}

Comments

Loading comments...

Tags

leetcode

string

greedy

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Minimum Changes To Make Alternating Binary String

HoningJS

Search Posts