"""
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
"""
class Solution:
def longestCommonPrefix(self,strs: list[str]) -> str:
list_length = len(strs)
shortest_length = len(strs[0])
for i in range(list_length):
length = len(strs[i])
if shortest_length > length:
shortest_length = length
shortest_char = strs[i]
char = [0]*len(shortest_char)
for i in range(shortest_length):
for str in strs:
if str[i] == shortest_char[i]:
char[i] +=1
for i in range(shortest_length):
if char[i] < list_length:
char_list = list(shortest_char)
return "".join(char_list[:i])
print(Solution.longestCommonPrefix(None,["flower","flow","flight"]))
result :
but in vscode ,i get an error :
UnboundLocalError: cannot access local variable 'shortest_char' where it is not associated with a value
^^^^^^^^^^^^^
char = [0]*len(shortest_char)
Line 11 in longestCommonPrefix (Solution.py)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ret = Solution().longestCommonPrefix(param_1)
Line 46 in _driver (Solution.py)
_driver()
Line 61 in <module> (Solution.py)
How can i solve this problem? In vscode, it goes through 3 for loop without any issue. I think in leetcode, it cant get variable between for loop, but why?
if shortest_length <= length
than your shortest_char
variable will not be defined. It is bad practice to define variables like that.