Skip to content

Instantly share code, notes, and snippets.

@perjerz
Created June 18, 2022 17:33
Show Gist options
  • Save perjerz/76611db4b4b98bb8fd01d01c6a0b98be to your computer and use it in GitHub Desktop.
Save perjerz/76611db4b4b98bb8fd01d01c6a0b98be to your computer and use it in GitHub Desktop.
/**
* @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