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.
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๋ฅผ ํ๋ฏ๋ก, ๊ฐ์ฅ ๊ธด ๋ฆฌ์คํธ์ ๊ธธ์ด๋ฅผ ๋ฆฌํดํด์ฃผ๋ฉด ๊ฐ๋จํ๊ฒ ํ ์ ์๋ ๋ฌธ์ ์๋ค.
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)
๊ฐ๋จํ์ง๋ง ๊ต์ฅํ ์ ์ฉํด์ ์ตํ๋๋ฉด ์์ฃผ ์ด์ฉํ ์ ์์ ๊ฒ ๊ฐ๋ค.