Slicing in Python, HackerRank Common Child

Viewed 433

Here is my code to solve a problem of finding the largest sequence of the same letters in two strings in the same order. My approach is basically to see if the letter is in both strings, then on that letter, the comparison string is sliced to avoid counting anything in the wrong order (EXAMPLE, SHA and HAP, have HA common, but SAH and HAP only have A or H in common.)

def commonChild(s1, s2):
stringA = []
a = s1
stringB = []
b = s2
y = 0
x = 0

for num in s1:
    if num in b[y:]:
        
        stringA.append(num)
        y = b.index(num) + 1
      
    else:
        pass

for num in s2:
    if num in a[x:]:
        
        stringB.append(num)
        x = a.index(num) + 1

    else:
        pass

theone = max(len(stringA),len(stringB))
return theone

It works with small tests (s1 = SALLY, s2= HARRY), but with large tests, I find that my slicing is not preforming correctly (slices occur at wrong index). Any suggestions on how to better my slicing.

0 Answers
Related