DeepRest

Consecutive Characters

Dec 13th, 2021 (edited)
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. #1 keep track of the cnt of one uniq char suffix length
  2. #O(n) time and 0(1) xtra space
  3. class Solution(object):
  4.     def maxPower(self, s):
  5.         res = cnt = 1
  6.         for i in range(1, len(s)):
  7.             if s[i] == s[i-1]:
  8.                 cnt += 1
  9.             else:
  10. #take max only when previous suffix is reset
  11.                 res, cnt = max(res, cnt), 1
  12. #for cases where the suffix of entire string is the ans
  13. #if we take max in if part then this is not required
  14.         return max(res, cnt)
  15.  
  16. #2 keep track of start of one uniq char suffix. This is two pointer/sliding window approach where window = largest suffix made of one character, start = st and end = i (the two pointers) in every iteration
  17. '''
  18. class Solution(object):
  19.    def maxPower(self, s):
  20.        res, st = 1, 0
  21.        for i in range(1, len(s)):
  22. #reset the start of suffix
  23.            if s[i] != s[i-1]:
  24.                res, st = max(res, i-st), i
  25.        return max(res, len(s)-st)
  26.        
  27. '''
  28.  
  29. #mod of #1 by keeping track of the char of suffix (previous character) which can be used in place of s[i-1]
  30. '''
  31. class Solution(object):
  32.    def maxPower(self, s):
  33.        res,char,cnt = 0,' ',0
  34.        for e in s:
  35.            if e == char:
  36.                cnt += 1
  37.            else:
  38.                res, char, cnt = max(res, cnt), e, 1
  39.  
  40.        return max(res, cnt)
  41.        
  42. '''
Add Comment
Please, Sign In to add comment