import re
class Solution:
countASay = "1" #Initialize countASay with base case
loopFlag = False #Flag to check if we need to check more than one pattern
def countAndSay(self, n: int) -> str:
if (n==1):
return str(n) #Base case
for i in range(2,n+1): #Genaral case, loop till nth countAndSay value is obtained
self.countPaternAndSay(self.countASay)
return self.countASay
def countPaternAndSay(self, res):
pat = res[0] + "+" #Start from the 0th index and search for pattern of 0th index value
match = re.search(pat, res)
countValue = match.end() - match.start()
startIndex = match.end() #Obtain new start index
tmpRes = str(countValue) + res[match.end() - 1]
if self.loopFlag == True: # loopFlag is True indicates that we had searched for more than one pattern hence append to the existing result
self.countASay=self.countASay+tmpRes
self.loopFlag = False
else:
self.countASay = tmpRes
res = res[startIndex:]
while bool(res):
self.loopFlag = True
return self.countPaternAndSay(res)