1446. Consecutive Characters LeetCode Solution

In this guide, you will get 1446. Consecutive Characters LeetCode Solution with the best time and space complexity. The solution to Consecutive Characters problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Consecutive Characters solution in C++
  4. Consecutive Characters solution in Java
  5. Consecutive Characters solution in Python
  6. Additional Resources
1446. Consecutive Characters LeetCode Solution image

Problem Statement of Consecutive Characters

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

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.

Constraints:

1 <= s.length <= 500
s consists of only lowercase English letters.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

1446. Consecutive Characters LeetCode Solution in C++

class Solution {
 public:
  int maxPower(string s) {
    int ans = 1;
    int count = 1;

    for (int i = 1; i < s.length(); ++i) {
      count = s[i] == s[i - 1] ? count + 1 : 1;
      ans = max(ans, count);
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

1446. Consecutive Characters LeetCode Solution in Java

class Solution {
  public int maxPower(String s) {
    int ans = 1;
    int count = 1;

    for (int i = 1; i < s.length(); ++i) {
      count = s.charAt(i) == s.charAt(i - 1) ? count + 1 : 1;
      ans = Math.max(ans, count);
    }

    return ans;
  }
}
// code provided by PROGIEZ

1446. Consecutive Characters LeetCode Solution in Python

class Solution:
  def maxPower(self, s: str) -> int:
    ans = 1
    count = 1

    for i in range(1, len(s)):
      count = count + 1 if s[i] == s[i - 1] else 1
      ans = max(ans, count)

    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.