Created
June 18, 2022 17:33
-
-
Save perjerz/76611db4b4b98bb8fd01d01c6a0b98be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string[]} strs | |
* @return {string} | |
*/ | |
var longestCommonPrefix = function(strs) { | |
const length = strs.length; | |
if (length == 0) { | |
return ''; | |
} else if (length == 1) { | |
return strs[0]; | |
} | |
let prefix = ''; | |
let match = false; | |
let stop = false; | |
const maxLength = Math.max(...strs.map(str => str.length)); | |
for (let j = 0; j < maxLength; j++) { | |
let character1 = strs[0][j]; | |
let count = 1; | |
for (let i = 1; i < strs.length; i++) { | |
if (character1 == strs[i][j]) { | |
count++; | |
} else { | |
stop = true; | |
break; | |
} | |
} | |
if (stop == true) { | |
break; | |
} | |
if (count == strs.length) { | |
prefix += character1; | |
} | |
} | |
return prefix; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment