- Related Questions & Answers
- Python program to check if a string contains all unique characters
- Program to find length of concatenated string of unique characters in Python?
- Program to find total unique duration from a list of intervals in Python
- Program to find number of sublists that contains exactly k different words in Python
- Program to count number of unique paths that includes given edges in Python
- Find all strings formed from characters mapped to digits of a number in Python
- Program to find length of longest substring which contains k distinct characters in Python
- Program to count number of elements in a list that contains odd number of digits in Python
- Program to count number of unique palindromes we can make using string characters in Python
- How to remove unique characters within strings in R?
- Find uncommon characters of the two strings in C++ Program
- Program to find minimum string size that contains given substring in Python
- Program to find sum of unique elements in Python
- Program to find least number of unique integers after K removals using Python
- Program to find the number of unique integers in a sorted list in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a string s of lowercase letters, we have to find the total number of substrings that contain one unique character.

So, if the input is like "xxyy", then the output will be 6 as substrings are [x, x, xx, y, y, yy]

To solve this, we will follow these steps −

- total := 0
- previous := blank string
- for each character c in s, do
- if c is not same as previous, then
- previous := c
- temp := 1

- otherwise,
- temp := temp + 1

- total := total + temp

- if c is not same as previous, then
- return total

Let us see the following implementation to get better understanding −

class Solution: def solve(self, s): total = 0 previous = '' for c in s: if c != previous: previous = c in_a_row = 1 else: in_a_row += 1 total += in_a_row return total ob = Solution() print(ob.solve("xxyy"))

"xxyy"

6

Advertisements