LeetCode, It's coding time
LeetCode day1:
Long common prefix. Level easy
Python solution
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not str:
return ""
strs.sort()
first_list = strs[0]
last_list = strs[-1]
long_common_prefix = ""
for i in range(len(first_list)):
if first_list[i] == last_list[i]:
long_common_prefix+=first_list[i]
else:
return long_common_prefix
return long_common_prefix
Javascript solution
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if(!strs || strs.length == 0){
return ""
}
strs.sort()
first_list = strs[0]
last_list = strs[strs.length-1]
long_common_prefix = ""
for(let i =0;i<first_list.length;i++){
if(first_list[i]==last_list[i]){
long_common_prefix+=first_list[i]
}else{
break
}
}
return long_common_prefix
}
Nhận xét
Đăng nhận xét