[leetcode #1446] Consecutive Characters


Problem


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.
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 consists of only lowercase English letters.

Idea


これは簡単な問題です.1文字からなるサブストリングの長さの最大値だけが必要で、戻ります.
私はsubstringの各アルファベットの最大長をarrayとして保存します.そうする必要はありません.最大値が現在のサブストリングの長さに比べて最大値より大きい場合は、最大値を変更することで実現できます.
各アルファベット文字に対応するサブ文字列の長さを格納する配列を作成します.指定された文字列を検索するときに、同じ文字でない文字が発生した場合、これまで計算されたsubstring長とarrayに格納されていたsubstring長を比較します.現在のsubstringの長さが長い場合はarrayの値を変更します.
文字列ナビゲーションが終了したら、最長のsubstring長を返します.

Solution

class Solution {
    public int maxPower(String s) {
        int[] power = new int[26];

        char c = s.charAt(0);
        int subLen = 1;

        for (int i=1; i < s.length(); i++) {
            if (c != s.charAt(i)) {
                power[c - 'a'] = Math.max(subLen, power[c - 'a']);
                c = s.charAt(i);
                subLen = 1;
                continue;
            }
            subLen++;
        }

        int res = 0;
        for (int i=0; i < 26; i++) {
            res = Math.max(res, power[i]);
        }

        return Math.max(res, subLen);
    }
}

Reference


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