File tree Expand file tree Collapse file tree 3 files changed +51
-0
lines changed Expand file tree Collapse file tree 3 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ # Longest Common Prefix
2+ [ Leetcode Link] ( https://leetcode.com/problems/longest-common-prefix/ )
3+
4+ ## Problem:
5+
6+ Write a function to find the longest common prefix string amongst an array of strings.
7+
8+ If there is no common prefix, return an empty string "".
9+
10+ ## Example:
11+
12+ ```
13+ Input: ["flower","flow","flight"]
14+ Output: "fl"
15+ ```
16+ ```
17+ Input: ["dog","racecar","car"]
18+ Output: ""
19+ Explanation: There is no common prefix among the input strings.
20+ ```
21+
22+ ## Note:
23+
24+ All given inputs are in lowercase letters ` a-z ` .
Original file line number Diff line number Diff line change 1+
2+ def longestCommonPrefix (strs ):
3+ """
4+ Write a function to find the longest common prefix string amongst an array of strings.
5+ If there is no common prefix, return an empty string "".
6+ """
7+ common = ""
8+ if len (strs ) == 0 :
9+ return common
10+ for i in range (len (strs [0 ])):
11+ prefix = strs [0 ][i ]
12+ for j in range (1 , len (strs )):
13+ if i >= len (strs [j ]) or strs [j ][i ] != prefix :
14+ return common
15+ common += prefix
16+ return common
17+
18+ input = ["flower" , "flow" , "flight" ]
19+ output = longestCommonPrefix (input )
20+ print ("Input:" , input )
21+ print ("Output:" , output )
22+
23+ input = ["dog" , "racecar" , "car" ]
24+ output = longestCommonPrefix (input )
25+ print ("Input:" , input )
26+ print ("Output:" , output )
Original file line number Diff line number Diff line change @@ -11,6 +11,7 @@ Languages used: Java and Python
1111- Easy
1212 - [ Sum of Even Numbers After Queries] ( Easy/SumOfEvenNumbersAfterQueries )
1313 - [ Next Greater Element 1] ( Easy/NextGreaterElement1 )
14+ - [ Longest Common Prefix] ( Easy/LongestCommonPrefix )
1415- Medium
1516 - [ Minimum Add to Make Parentheses Valid] ( Medium/MinimumAddtoMakeParenthesesValid )
1617 - [ Distribute Coins in Binary Tree] ( #Medium/DistributionCoinsInBinaryTree )
You can’t perform that action at this time.
0 commit comments