#!/usr/bin/python3 # ==================================================================== # two pointers - find the longest substring of the same character # ==================================================================== # -------------------------------------------------------------------- # ---- find the next single character substring starting at idxa # ---- (start and end indexes) # -------------------------------------------------------------------- def next_substring(idxa: int,string: str) -> tuple: ''' find the next single character substring''' slen = len(string) idxb = idxa while True: if idxb >= slen or string[idxa] != string[idxb]: ssstr = string[idxa:idxb] sslen = len(ssstr) return (idxa,idxb-1,sslen,ssstr) idxb += 1 # -------------------------------------------------------------------- # ---- find the longest single character substring # ---- (first one if there are duplicate lengths) # ---- loc = (strt_index, end_index, length) # -------------------------------------------------------------------- def longest_substring(string: str) -> tuple: ''' find the first longest single character substring''' idxa: int = 0 # start next substring search index loc: tuple = (0,0,0) # longest substring location # ---- is there a string? if len(string) < 1: return loc # ---- process the string while True: (idxa,idxb,sublen,substr) = next_substring(idxa,string) ##print(f'next_substr: idxa={idxa} idxb={idxb} ' +\ ## f'sslen={sublen} ssstr="{substr}"') if sublen > loc[2]: loc = (idxa,idxb,sublen) if idxb+1 >= len(string): break idxa = idxb + 1 return loc # -------------------------------------------------------------------- # ---- main # -------------------------------------------------------------------- if __name__ == '__main__': # ---- longest sequence character is "v" # ---- location is index 32 to 37 (inclusive) # ---- length 6 # ---- 1 2 3 4 # ---- 012345678901234567890123456789012345678901 bigstr: str = 'aghrsssssdsfgggghaannozzxzttrrrrvvvvvvzzzz' scale0 = '0 1 2 3 4 5' scale1 = '012345678901234567890123456789012345678901234567890' strings: str = ['','a','aaa','abbc','aabbbcc','xyzzzz', 'xyz','xyyzz','xxyyz','abcc','aaabc',bigstr] for string in strings: print() print('---- TEST STRING ------------------------------------') ##print(f'---- {scale0}') ##print(f'---- {scale1}') print(f'string : "{string}"') if len(string) < 1: print('empty string') continue loc = longest_substring(string) print(f'substring: "{string[loc[0]:loc[1]+1]}"') print(f'location : {loc}')