Similar Problems

Similar Problems not available

Substrings Of Size Three With Distinct Characters - Leetcode Solution

Companies:

LeetCode:  Substrings Of Size Three With Distinct Characters Leetcode Solution

Difficulty: Easy

Topics: string sliding-window hash-table  

Problem Statement:

A string is good if there are no repeated characters.

Given a string s, return the number of good substrings of length three in s.

A substring of length three is a contiguous substring of s of length three.

Example:

Input: s = "xyzzaz" Output: 1 Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". The only good substring of length 3 is "xyz".

Solution:

Approach:

We can solve this problem by simply iterating through the string s and counting the number of good substrings of length three.

To count the number of good substrings, we need to check if all the characters in the substring are distinct. There are only 26 possible characters, so we can use an array of size 26 to count the occurrences of each character in the substring.

Algorithm:

Initialize a variable count to 0 Iterate over the string s from index 2 to the end for each index i, check if all the three characters s[i-2], s[i-1], and s[i] are distinct If they are, increment the count by 1 Return the count

Code:

class Solution { public: int countGoodSubstrings(string s) { int count = 0; for (int i = 2; i < s.length(); i++) { if (s[i-2] != s[i-1] && s[i-1] != s[i] && s[i] != s[i-2]) { count++; } } return count; } };

Substrings Of Size Three With Distinct Characters Solution Code

1