Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9dc3257

Browse files
Add longest common prefix function
Implement solution for finding the longest common prefix among a list of strings.
1 parent 26b899f commit 9dc3257

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

‎day-29/longest_common_prefix.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Problem: Longest Common Prefix
2+
# Link: https://leetcode.com/problems/longest-common-prefix/description/
3+
# Tags: String
4+
# Approach: Take the first word as a template and compare each character index
5+
# against all other words; stop at the first mismatch or length overrun.
6+
# Time Complexity: O(S) where S is the sum of all characters
7+
# Space Complexity: O(1)
8+
9+
10+
class Solution:
11+
def longestCommonPrefix(self, strs):
12+
if not strs:
13+
return ""
14+
first = strs[0]
15+
for i in range(len(first)):
16+
ch = first[i]
17+
for w in strs[1:]:
18+
if i == len(w) or w[i] != ch:
19+
return first[:i]
20+
return first

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /