Skip to content

Commit 44d7571

Browse files
authored
Merge pull request #1160 from ivan1016017/january22
adding longest common prefix
2 parents 1b7511c + ebae23b commit 44d7571

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def longestCommonPrefix(self, strs: List[str]) -> str:
6+
7+
if not strs:
8+
return ''
9+
else:
10+
min_strs, max_strs = min(strs), max(strs)
11+
count = 0
12+
13+
len_min_strs = len(min_strs)
14+
15+
for i in range(len_min_strs):
16+
if min_strs[i] != max_strs[i]:
17+
break
18+
else:
19+
count += 1
20+
21+
return min_strs[:count]
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_13\
3+
.longest_common_prefix import Solution
4+
5+
6+
class LongestCommonPrefixTestCase(unittest.TestCase):
7+
8+
def test_longest_common_prefix(self):
9+
solution = Solution()
10+
output = solution.longestCommonPrefix(strs=["flower","flow","flight"])
11+
target = 'fl'
12+
self.assertEqual(target, output)
13+
14+
def test_longest_no_common_prefix(self):
15+
solution = Solution()
16+
output = solution.longestCommonPrefix(strs=["dog","racecar","car"])
17+
target = ''
18+
self.assertEqual(target, output)
19+
20+
def test_longest_common_prefix_null_list(self):
21+
solution = Solution()
22+
output = solution.longestCommonPrefix(strs=[])
23+
target = ''
24+
self.assertEqual(target, output)

0 commit comments

Comments
 (0)