1446. Consecutive Characters

Link: https://leetcode.com/problems/consecutive-characters/

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.

題目翻譯:

就找出字串裡的字母最大連續數量。

程式思路:

easy

class Solution {
public:
    int maxPower(string s) {
        int power = 0;
        int max_power = 0;
        char c = '\0';
        for(auto it : s)
        {
            if(it != c)
                power = 1;
            else
                power++;

            c = it;
            if(power > max_power) max_power = power;
        }
        return max_power;
    }
};

  目錄