Consecutive Chars, O(n)-time, O(1)-space

Problem is here: https://leetcode.com/problems/consecutive-characters/

Explanation:
  • Base case when the string is empty - zero
  • From that point on, max is at least 1
  • Start from the second char
  • Look to the previous one, if the same, increment the current count (you still have a candidate)
  • Otherwise, the current becomes 1
  • Always make max = Max( max, current )
Code is below, cheers, ACC.


public class Solution
{
    public int MaxPower(string s)
    {
        if (String.IsNullOrEmpty(s)) return 0;

        int max = 1;
        int current = 1;
        for (int i = 1; i < s.Length; i++)
        {
            if (s[i] == s[i - 1]) current++;
            else current = 1;
            max = Math.Max(max, current);
        }

        return max;
    }

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval