Skip to content

Latest commit

 

History

History
82 lines (64 loc) · 1.85 KB

_1759. Count Number of Homogenous Substrings.md

File metadata and controls

82 lines (64 loc) · 1.85 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 10, 2024

Last updated : July 01, 2024


Related Topics : Math, String

Acceptance Rate : 57.55 %


Solutions

C

long helper(long orig, long substrLen) {
    return (orig + (substrLen + 1) * substrLen / 2) % (1000000000 + 7);
}

int countHomogenous(char * s){
    int leftIndx = 0;
    int currentIndx = 0;
    char leftChar = *s;
    long output = 0;

    while (*s) {
        if (*s != leftChar) {
            leftChar = *s;
            output = helper(output, (long) (currentIndx - leftIndx));
            leftIndx = currentIndx;
        }

        currentIndx++;
        s++;
    }
    output = helper(output, (long) (currentIndx - leftIndx));

    return output;

}

Java

class Solution {
    public int countHomogenous(String s) {
        int leftIndx = 0;
        char leftChar = s.charAt(0);

        long output = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != leftChar) {
                leftChar = s.charAt(i);
                output += helper(i - leftIndx);
                output %= (1000000000 + 7);
                leftIndx = i;
            }
        }
        output += helper(s.length() - leftIndx);
        output %= (1000000000 + 7);

        return (int) output;
    }
    public long helper(long numChars) {
        return (1 + numChars) * numChars / 2;
    }
}