python Find the longest substring without any number and at least one upper case character -
i've been stuck trying figure out how find longest substring no numbers , @ least 1 uppercase. when comes @ least 1 upper case. tried iterating on string , appending element new list. if element came number, tried see if of elements in new list had capital letter. appricated. thank
algorithm overview:
iterate on string, if see number add substring before number dictionary, key length of substring , value substring. return max-length substring.
the code follows:
def longestsubstring(s): max_length = 0 tmp_length = 0 tmp_uppercase_count = 0 tmp_string = "" strings = {} nums = '0123456789' s_length = len(s) in range(s_length): if s[i] not in nums: if s[i].upper() == s[i]: tmp_uppercase_count += 1 tmp_length += 1 tmp_string += s[i] if tmp_uppercase_count > 0 , == s_length - 1: strings[tmp_length] = tmp_string max_length = max(max_length, tmp_length) else: if tmp_uppercase_count > 0: strings[tmp_length] = tmp_string max_length = max(max_length, tmp_length) tmp_length = 0 if != s_length - 1: tmp_string = "" tmp_uppercase_count = 0 if len(strings) == 0 , tmp_uppercase_count > 0: return tmp_string elif len(strings) == 0: return "" else: return strings[max_length] note instead of going shorter code, looked more time complexity. code runs in o(n) time.
Comments
Post a Comment