The Longest Common Prefix solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Longest Common Prefix
C++, Python and TypeScript solutions for Longest Common Prefix.
Solution files
Python•longest-common-prefix/synced-solution.py
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs: return ""
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
if not prefix: return ""
return prefix
C++•longest-common-prefix/synced-solution.cpp
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
string prefix = strs[0];
for (auto& s : strs) {
while (s.find(prefix) != 0) {
prefix = prefix.substr(0, prefix.size()-1);
if (prefix.empty()) return "";
}
}
return prefix;
}
};
TypeScript•longest-common-prefix/synced-solution.ts
function longestCommonPrefix(strs: string[]): string {
if (!strs.length) return "";
let prefix = strs[0];
for (const s of strs) {
while (!s.startsWith(prefix)) {
prefix = prefix.slice(0, -1);
if (!prefix) return "";
}
}
return prefix;
}