반응형
1. 문제
https://leetcode.com/problems/longest-common-prefix/
2. 코드
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
let common = "";
let lengthOfStrs = strs.map((el) => el.length)
let shortestStr = lengthOfStrs.indexOf(Math.min(...lengthOfStrs));
for(let i=0;i<strs[shortestStr].length;i++){
let allSame = true;
for(let j=0;j<strs.length;j++){
if(strs[j][i] !== strs[shortestStr][i]){
allSame = false;
break;
}
}
if(allSame) common += strs[shortestStr][i];
else break;
}
return common;
};
반응형
'리트코드 > easy' 카테고리의 다른 글
[리트코드] 70. Climbing Stairs - js (메모이제이션) (0) | 2023.09.07 |
---|---|
[리트코드] 2806. Account Balance After Rounded Purchase - js (0) | 2023.09.05 |
[리트코드] 205. Isomorphic Strings - js (0) | 2023.09.02 |
[리트코드] 121. Best Time to Buy and Sell Stock - js (0) | 2023.08.29 |
[리트코드] 20. Valid Parentheses - js (0) | 2023.08.23 |