We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
thanks for the link, I had stubbornly been banging my head on this one for quite a while (some days) before checking in here :)
So if someone else is struggling with their python3 solution here is mine with explanations on what is happening and why.
To see the sequence of letters just uncomment the lines working on the lcs_letters matrix, it wont pass all tests though
defcommonChild(s1,s2):# row 0 = 0, column 0 = 0l1=len(s1)l2=len(s2)# we only need history of previous rowlcs=[[0]*(len(s1)+1)for_inrange(2)]#lcs_letters = [['']*(len(s1)+1) for _ in range(2)]# i in s1 = i+1 in lcsforiinrange(l1):# get index pointers for current and previous rowli1=(i+1)%2li=i%2# j in s1 = j+1 in lcsforjinrange(l2):# i and j are used to step forward in each string.# Now check if s1[i] and s2[j] are equal ifs1[i]==s2[j]:# Now we have found one longer sequence # than what we had previously found.# so add 1 to the length of previous longest# sequence which we could have found at# earliest previous position of each string,# therefore subtract -1 from both i and jlcs[li1][j+1]=(lcs[li][j]+1)#lcs_letters[li1][j+1]=lcs_letters[li][j]+s1[li]# if not matching pair, then# get the biggest previous valueeliflcs[li1][j]>lcs[li][j+1]:lcs[li1][j+1]=lcs[li1][j]#lcs_letters[li1][j+1]=lcs_letters[li1][j]else:lcs[li1][j+1]=lcs[li][j+1]#lcs_letters[li1][j+1]=lcs_letters[li][j+1]#print(lcs_letters[(i+1)%2][j+1])returnlcs[(i+1)%2][j+1]
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Common Child
You are viewing a single comment's thread. Return to all comments →
thanks for the link, I had stubbornly been banging my head on this one for quite a while (some days) before checking in here :)
So if someone else is struggling with their python3 solution here is mine with explanations on what is happening and why.
To see the sequence of letters just uncomment the lines working on the lcs_letters matrix, it wont pass all tests though