Examples of invalid strings: AA, ABAA, ABACAA, ABACABAC, ABACABAB
Examples of valid strings: AB, ABC, ABA, ABACABADAB, ABACABCACBABCABACABCACBACAB
I call this function every time I add a new character to the string. So strings like ABABC will never get checked by the function since the string will already be invalid once the second B is added.
I need the absolute fastest way to check this in a function.
So far I've come up with 2 relatively slow functions:
def is_valid(s):
if len(s) < 2:
return True
# Are last two chars the same
if s[-1] == s[len(s)-2]:
return False
# Get array of indexes where last char appears and reverse it
indexes = [m.start() for m in re.finditer(s[-1], s[:-1])]
indexes = indexes[::-1]
for index in indexes:
a = s[index+1:]
if index - len(a) + 1 < 0:
return True
b = s[index-len(a)+1 : index+1]
if a == b:
return False
return True
and
def is_valid(s):
# Reverse string
s = s[::-1]
substring = ""
for i in range(len(s)):
substring += s[i]
if len(s) >= i+1+len(substring) and s[i+1 : i+1+len(substring)] == substring:
return False
return True
If there's not much to be improved here, would there be a noticable performance increase in C++/C# or Java?