- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Longest Common Prefix in Python
Suppose we have a set of strings in an array. We have to find the Longest Common Prefix amongst the string in the array. Here we will assume that all strings are lower case strings. And if there is no common prefix, then return “”.
So if the array of a string is like ["school", "schedule","Scotland"], then the Longest Common Prefix is “sc” as this is present in all of these string.
To solve this, we will take the first string as curr, now take each string from the array and read them character by character, and check the characters between curr, and the taken string one by one. If they are same go for next character, otherwise break the loop, and update the curr as the substring that has matched.
Let us see the implementation to get a better understanding
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return "" current = strs for i in range(1,len(strs)): temp = "" if len(current) == 0: break for j in range(len(strs[i])): if j<len(current) and current[j] == strs[i][j]: temp+=current[j] else: break current = temp return current input_list = ["school","schedule","scotland"] ob1 = Solution() print(ob1.longestCommonPrefix(input_list))
- Find minimum shift for longest common prefix in C++
- Program to find longest common prefix from list of strings in Python
- Longest Happy Prefix in C++
- Longest Common Subsequence
- SequenceMatcher in Python for Longest Common Substring.
- Program for longest common directory path in Python
- Longest Common Subsequence in C++
- Find the longest common prefix between two strings after performing swaps on second string in C++
- C++ Program for Longest Common Subsequence
- Java Program for Longest Common Subsequence
- Program to find length longest prefix sequence of a word array in Python
- K Prefix in Python
- Program to find length of longest common subsequence of three strings in Python
- Program to find longest prefix that is also a suffix in C++
- Python - Prefix sum list