LeetCode-in-Java

3803. Count Residue Prefixes

Easy

You are given a string s consisting only of lowercase English letters.

A prefix of s is called a residue if the number of distinct characters in the prefix is equal to len(prefix) % 3.

Return the count of residue prefixes in s.

A prefix of a string is a non-empty substring that starts from the beginning of the string and extends to any point within it.

Example 1:

Input: s = “abc”

Output: 2

Explanation:

Example 2:

Input: s = “dd”

Output: 1

Explanation:

Example 3:

Input: s = “bob”

Output: 2

Explanation:

Constraints:

Solution

public class Solution {
    public int residuePrefixes(String s) {
        int n = s.length();
        int count = 0;
        int p = 0;
        char c1 = s.charAt(p);
        while (p < n && c1 == s.charAt(p)) {
            if (++p % 3 == 1) {
                count++;
            }
        }
        if (p >= n) {
            return count;
        }
        char c2 = s.charAt(p);
        while (p < n && (c1 == s.charAt(p) || c2 == s.charAt(p))) {
            if (++p % 3 == 2) {
                count++;
            }
        }
        return count;
    }
}