Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Longest Common Prefix

class Solution:
    def longestCommonPrefix(self, strs):
        result = ""
        
        for i in range(len(strs[0])):                       # Pick any word in the list and loop through its length. Thats the number of times youre to loop thu the list
                                                            # because your answer cant be longer in length than any word in the list
            for word in strs:                                  # loop through the words in the the list so you can use the word[i] to acces the letters of each word                
                if i == len(word) or word[i] != strs[0][i]:     # stop code by returning result if loop count(i) is same as length of your chosen word 
                    return result                               # or if theres no more similar between other words and your chosen word
            result = result + strs[0][i]                        # otherwise keep adding the similar letters that occur in same position in all the words to the result 
 
        

Task = Solution()
print(Task.longestCommonPrefix(["flower","flow","flight"]))
print(Task.longestCommonPrefix(["dog","racecar","car"]))
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #Longest #Common #Prefix
ADD COMMENT
Topic
Name
9+3 =