[leetcode #1446] Consecutive Characters

Seongyeol Shin·2021년 12월 13일
0

leetcode

목록 보기
102/196
post-thumbnail

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

간단한 문제다. 하나의 문자로만 이루어진 substring의 길이 중 최대값을 구해서 리턴하면 된다.

나는 substring 중 알파벳의 각 문자에 해당하는 최대길이를 array로 저장했는데 그럴 필요는 없었다. 최대값과 현재 substring의 길이를 비교해 최대값보다 클 경우 최대값을 바꾸는 방식으로 구현해도 된다.

각 알파벳 문자에 해당하는 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/

profile
서버개발자 토모입니다

0개의 댓글