Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Longest Common Prefix Method 2

class Solution:
    def longestCommonPrefix(self, strs):
        result = []
        for i in zip(*strs):
            if len(set(i)) != 1:
                break
            result.append(i[0])
        return "".join(result)     

"""The zip() method returns a zip object, which is an iterator of tuples where 
the first item in each passed iterator is paired together, and then the second item in 
each passed iterator are paired together etc.
If the passed iterators have different lengths, the iterator with the least items 
decides the length of the new iterator.

set() method is used to convert any of the iterable to sequence of iterable elements 
with distinct elements, commonly called Set. 
"""                 
 
        

Task = Solution()
print("3a. ",Task.longestCommonPrefix(["flower","flow","flight"]))
print("3b. ",Task.longestCommonPrefix(["dog","racecar","car"]))
 
PREVIOUS NEXT
Tagged: #Longest #Common #Prefix #Method
ADD COMMENT
Topic
Name
3+5 =