LeetCode 1180: Count Substrings with Only One Distinct Letter Solution

Master LeetCode problem 1180 (Count Substrings with Only One Distinct Letter), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1180. Count Substrings with Only One Distinct Letter

Problem Explanation

Explanation

Given a string S, we need to count the number of substrings with only one distinct letter.

To solve this problem, we can iterate through the string S and count the number of consecutive characters that are the same. For each group of consecutive characters, we can calculate the number of substrings with only one distinct letter that can be formed using the formula n * (n + 1) / 2, where n is the length of the group.

Solution Code

class Solution {
    public int countLetters(String S) {
        int count = 0;
        int consecutive = 1;
        
        for (int i = 1; i < S.length(); i++) {
            if (S.charAt(i) == S.charAt(i - 1)) {
                consecutive++;
            } else {
                count += (consecutive * (consecutive + 1)) / 2; // Calculate number of substrings
                consecutive = 1;
            }
        }
        
        count += (consecutive * (consecutive + 1)) / 2; // Calculate for the last group
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1180 (Count Substrings with Only One Distinct Letter)?

This page provides optimized solutions for LeetCode problem 1180 (Count Substrings with Only One Distinct Letter) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1180 (Count Substrings with Only One Distinct Letter)?

The time complexity for LeetCode 1180 (Count Substrings with Only One Distinct Letter) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1180 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1180 in Java, C++, or Python.

Back to LeetCode Solutions