๐Ÿง  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.

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

๋‚˜์˜ ํ’€์ด

def maxPower(self, s: str) -> int:
    count = maxCount = 1
    last = s[0]
    for c in s[1:]:
        if c == last:
            count += 1
        maxCount = max(count, maxCount)
        if c != last:
            count = 1
            last = c
    return maxCount

๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

from itertools import groupby


def maxPower(self, s: str) -> int:
     return max(len(list(j)) for _,j in groupby(s))

itertools์˜ groupby ํ•จ์ˆ˜๋ฅผ ์ฒ˜์Œ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค. groupby์˜ ๋™์ž‘์€ ์ดํ„ฐ๋ ˆ์ดํ„ฐ์˜ ํ‚ค ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค break๋ฅผ ํ•˜๋ฏ€๋กœ, ๊ฐ€์žฅ ๊ธด ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด๋ฅผ ๋ฆฌํ„ดํ•ด์ฃผ๋ฉด ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€๋‹ค.

groupby()

class groupby:

    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D

    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key
        self.it = iter(iterable)
        self.tgtkey = self.currkey = self.currvalue = object()

    def __iter__(self):
        return self

    def __next__(self):
        self.id = object()
        while self.currkey == self.tgtkey:
            self.currvalue = next(self.it)
            self.currkey = self.keyfunc(self.currvalue)
        self.tgtkey = self.currkey
        return (self.currkey, self._grouper(self.tgtkey, self.id))

    def _grouper(self, tgtkey, id):
        while self.id is id and self.currkey == tgtkey:
            yield self.currvalue
            try:
                self.currvalue = next(self.it)
            except StopIteration:
                return
            self.currkey = self.keyfunc(self.currvalue)

๊ฐ„๋‹จํ•˜์ง€๋งŒ ๊ต‰์žฅํžˆ ์œ ์šฉํ•ด์„œ ์ตํ˜€๋‘๋ฉด ์ž์ฃผ ์ด์šฉํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๋‹ค.

References


Written by@ugaemi
Record things I want to remember

๐Ÿฑ GitHub๐Ÿ“š Reading Space