Longest Common Suffix from the listed words

791 views Asked by At

Trying to reiterate backward the codes so as to find common suffix of the entered array of words say:

LongestCommonSuffix(['celebration', 'opinion', 'decision', 'revision'])

To get "ion" as output

This gives me the Longest Common Prefix BUT I need to change the loop to do the same but from the end of each word in the entered list without using Binary manipulation just LOOPING

def fun(strs): 
    res = ''

    for i in range(len(strs[0])):
        for s in strs:
            if i == len(s) or s[i] != strs[0][i]:
                return res
        res += strs[0][i]
    return res
2

There are 2 answers

0
wovano On

You could create a variable common_suffix, make that equal to the first word, and then for each next word check if that word ends with that common suffix. If it doesn't, the common suffix is invalid, so try to shorten it until it does.

In code:

def LongestCommonSuffix(strs):
    common_suffix = strs[0]
    for next_word in strs[1:]:
        while not next_word.endswith(common_suffix):
            common_suffix = common_suffix[1:]
    return common_suffix

print(LongestCommonSuffix(['celebration', 'opinion', 'decision', 'revision']))

This prints ion.

Note that this code works because common_suffix would be an empty string if all words are completely different. And each word ends with an empty string (for example 'test'.endswith('') is True), so the while loop will always quit. You could add additional logic to break from the loop earlier, but if performance is not critical, I would stick with the simple code :-)

0
yairchu On
os.path.commonprefix([w[::-1] for w in words])[::-1]