A substring is a string of characters that is contained in another string. For example,…
- User
A substring is a string of characters that is contained in another string. For example, the substrings of "abcdef" could be "abc", "bc", "cdef", "e" and so on. But, "bca", "ace", and "g" are not substrings of "abcdef".
Your task is to count the number of non-empty substrings possible of a given string such that all characters in that substring are same. If two substrings contains same alphabets but appear at different positions in that given string, they are still considered to be different. Input
A single string without spaces
Output
a single integer denoting the number of substrings as described above
Constraints length of string will be between 1 and 100 all characters of string will be small case alphabets only
SAMPLE INPUT xxxyx
SAMPLE OUTPUT 8
Explanation
four occurrences of substring "x"
one occurrence of substring "y"
two occurrences of substring "xx"
one occurrence of substring "xxx"
= total 8
Assistant
We need to count number of non-empty substrings where all characters are the same. Basically count of all contiguous substrings that consist of a single repeated character. For string length up to 100, we can compute by scanning and counting runs of same character. For each maximal run of length L of a character, the number of substrings that are all that character (and non-empty) is L*(L+1)/2. Because you can choose start and end within run, any contiguous subsegment is all same character. Sum over runs. This counts all such substrings. Example: "xxxyx" -> runs: "xxx" length 3 gives 3*4/2=6; then "y" length 1 gives 1; then "x" length 1 gives 1; total=8. Yes.
Edge cases: single character string length 1 gives 1.
Implement: read string s, iterate over indices, maintain count of current run length, reset when char changes. Sum.
Complexity O(n).
We'll output integer.
Thus answer. We can count the substrings by scanning the string and summing the contributions from each maximal block of identical characters. For a block of length L, it contributes L*(L+1)//2 substrings where all characters are the same.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.