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

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons