
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
Example (Python)
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return "" current = strs[0] 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))
Input
["school","schedule","scotland"]
Output
"sc"
- Related Articles
- Program to find longest common prefix from list of strings in Python
- Find minimum shift for longest common prefix in C++
- Longest Happy Prefix in C++
- SequenceMatcher in Python for Longest Common Substring.
- Find the longest common prefix between two strings after performing swaps on second string in C++
- Program for longest common directory path in Python
- Program to find length longest prefix sequence of a word array in Python
- Longest Common Subsequence
- Longest Common Subsequence in C++
- K Prefix in Python
- Find the longest sub-string which is prefix, suffix and also present inside the string in Python
- Program to find longest prefix that is also a suffix in C++
- Program to find length of longest common subsequence of three strings in Python
- C++ Program for Longest Common Subsequence
- Java Program for Longest Common Subsequence
