当前位置:网站首页>String longest common prefix
String longest common prefix
2022-07-25 10:31:00 【scwMason】
Write a function to find the longest common prefix in the string array .
If no common prefix exists , Returns an empty string "".
Example 1:
Input : ["flower","flow","flight"]
Output : "fl"
Example 2:
Input : ["dog","racecar","car"]
Output : ""
explain : Input does not have a common prefix .
explain :
All inputs contain only lowercase letters a-z .
link :https://leetcode-cn.com/problems/longest-common-prefix
analysis
Method 1
It's also my stupid way , Is to select a benchmark string , Then match one by one according to the prefix order , This time complexity has reached O(m*n*N) So it's bad
Method 2
utilize Python The character of string , such as aba,abb,abac Three strings ,ascall The largest size is abb, So this feature shows that there is a loop string from scratch in the comparison process , So we can :
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
min_str=min(strs)
max_str=max(strs)
for i,m in enumerate(min_str):
if m!=max_str[i]:
return min_str[:i]
return min_strMethod 3
It's also the use of python Medium zip Method , use zip The built-in method aligns the left side of the string , Then compress longitudinally , And then use set Method to check the string length after de duplication :
def longestCommonPrefix(self, strs):
if not strs: return ""
ss = list(map(set, zip(*strs))) # because zip Method will finally return the Yuanzu set , So we need to use list()
res = ""
for i, x in enumerate(ss):
x = list(x)
if len(x) > 1:
break
res = res + x[0]
return res Take our input example
["flower","flow","flight"] This set uses zip After method , Namely :
["fff","lll","ooi","wwg"]
So after the weight is removed :
["f","l","oi","wg"]
Therefore, the judgment length is greater than 1 It means that there are different letters .
边栏推荐
- About the jar package of slf4j log4j log4j2 used together
- Pow(x,n)
- 切换 shell 命令行终端(bash/zsh)后,conda 无法使用: command not found
- 集合的创建,及常用方法
- 1、 The difference between unittest framework and pytest framework
- 一、unittest框架和pytest框架的区别
- 常用类的小知识
- 软件测试笔记,测试用例设计
- Attention is all you need 论文精读笔记 Transformer
- 三、unittest测试用例五种运行方式
猜你喜欢
随机推荐
10. Expect interaction free
2.shell脚本之条件语句
JS encryption parameter positioning
Configure FTP virtual user and access control
Trojang attack on neural networks paper reading notes
Multithreading deadlock and synchronized
4.隔壁小孩都会的,各种shell符号{}[]等
js 哈希表 02
For cycle: daffodil case
mongoDB的使用
Software test notes, test case design
Notes on building dompteur container
Basic knapsack problem
Test plan and test plan
Pytorch code template (CNN)
使用px2rem不生效
21. Merge Two Sorted Lists
2.介绍部署LAMP平台+DISCUZ论坛
Angr (x) - official document (Part1)
Angr (IV) -- angr_ ctf









