4 Consecutive Character --> Leetcode November 2020 Challenge

4 Consecutive Character --> Leetcode November 2020 Challenge

Question

Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.

Return the power of the string.

Example 1:

Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.

Example 2:

Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.

Example 3:

Input: s = "triplepillooooow"
Output: 5

Example 4:

Input: s = "hooraaaaaaaaaaay"
Output: 11

Example 5:

Input: s = "tourist"
Output: 1

Constraints

1 <= s.length <= 500 s contains only lowercase English letters.

Solution

Consecutive Characters, this problem is a very easy one and requires simple knowledge of array traversal. The algorithm to solve this problem is

  1. Create local_max variable to assign the count of repeated character and max_value variable to keep track of the maximum value of local_max
  2. Initially we assign the local_max and max_value both 1. This is because we are taking the first character manually.
  3. Now we start traversing the string with the second character. If the current character is the same as the previous character then we are having a repetition of the previous character so we can increase the local_max variable by 1. However, if the current character is not equal to the previous character then we know we are getting a different character so we are resetting the local_max to 1.
  4. Finally we are taking max between local_max and max_value and returning max_value.

The complete solution of the code is

class Solution {
public:
    int maxPower(string s) {
        int len = s.size();
        int local_max = 1;
        int max_value = 1;
        for(int i = 1; i < len; i++){
            if(s[i] == s[i-1]){
                local_max++;
            }
            else {
                local_max = 1;
            }
            max_value = max(max_value,local_max);
        }
        return max_value;
    }
};

The time complexity of the solution is O(N) because we are traversing through each element 1 time. The space complexity is O(1) as we are only using a fixed number of variables.

I hope you all liked the solution. Please let me know in the comment section if we can do better than this.

Thank you.