当前位置:网站首页>Longest common prefix and
Longest common prefix and
2022-07-03 07:18:00 【darabiuz】
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 :strs = [“flower”,“flow”,“flight”]
Output :“fl”
Example 2:
Input :strs = [“dog”,“racecar”,“car”]
Output :""
explain : Input does not have a common prefix .
// First assume the longest public prefix ans Is the first , Traverse each subsequent string , And ans Go through one by one , Record subscript if different , Intercept ans return
var longestCommonPrefix = function (strs) {
if (!strs.length) return ''
let ans = strs[0]
// Traversal string array
for (let i = 1; i < strs.length; i++) {
// Traversing every character of a string
let tmp
if (!strs[i].length) return ''
for (let j = 0; j < strs[i].length; j++) {
// and ans contrast , Different ends convenience , here j It's the next one in a different position index
if (ans[j] != strs[i][j]) {
tmp = j
break
}
tmp = j + 1
}
ans = ans.substr(0, tmp)
}
return ans
};
longestCommonPrefix(["abab", "aba", ""])
边栏推荐
- Le Seigneur des anneaux: l'anneau du pouvoir
- [vscode - vehicle plug-in reports an error] cannot find module 'xxx' or its corresponding type declarations Vetur(2307)
- Chrome 98 Private Network Access problem w/ disabled web security: Request had no target IP address
- Deep learning parameter initialization (I) Xavier initialization with code
- Hash table, generic
- C WinForm framework
- In depth analysis of reentrantlock fair lock and unfair lock source code implementation
- 4everland: the Web3 Developer Center on IPFs has deployed more than 30000 dapps!
- SharePoint modification usage analysis report is more than 30 days
- Use of framework
猜你喜欢
Inno setup production and installation package
Le Seigneur des anneaux: l'anneau du pouvoir
[solved] sqlexception: invalid value for getint() - 'Tian Peng‘
SecureCRT取消Session记录的密码
691. Cube IV
Specified interval inversion in the linked list
Pits encountered in the use of El checkbox group
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
《指环王:力量之戒》新剧照 力量之戒铸造者亮相
7.2 brush two questions
随机推荐
Interview questions about producers and consumers (important)
IP home online query platform
深度学习参数初始化(一)Xavier初始化 含代码
II. D3.js draw a simple figure -- circle
SharePoint modification usage analysis report is more than 30 days
When MySQL inserts Chinese into the database, there is a diamond question mark garbled code
Notes on the core knowledge of Domain Driven Design DDD
sharepoint 2007 versions
php artisan
【最詳細】最新最全Redis面試大全(50道)
Thoughts in Starbucks
gstreamer ffmpeg avdec解码数据流向分析
Common APIs
C code production YUV420 planar format file
Specified interval inversion in the linked list
php artisan
Thoughts on project development
In depth analysis of reentrantlock fair lock and unfair lock source code implementation
3311. Longest arithmetic
Laravel frame step pit (I)