[Leetcode] 14. Longest Common Prefix
Source
https://leetcode.com/problems/longest-common-prefix/
Longest Common Prefix - LeetCode
Can you solve this real interview question? Longest Common Prefix - Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow"
leetcode.com
Code
var longestCommonPrefix = function (strs) {
for (let i = 0; i < strs[0].length; i++) {
let char = strs[0][i];
for (let j = 0; j < strs.length; j++) {
if (char !== strs[j][i]) {
return strs[0].substring(0, i);
}
}
}
return strs[0];
};
How to solve?
1. 리스트의 첫 요소의 각 문자를 순회하면서 char에 저장 해준다.
2. 리스트의 각 요소를 순회하며 각각의 문자 하나 하나가 char와 일치하지 않는 경우를 찾는다.
3. 2의 경우를 찾는다면 substring 함수를 반환한다.
(substring 함수는 첫번째 요소부터 두번째 요소 - 1까지의 요소 를 반환한다)
4. 전부 순회할때까지 값이 return되지 않는다면 strs의 0번째 요소를 반환한다.
'Problem solve' 카테고리의 다른 글
[Leetcode] 28. Find the Index of the First Occurrence in a String (JavaScript) (0) | 2023.05.06 |
---|---|
[LeetCode] 35. Search Insert Position (Javascript) (0) | 2023.04.24 |
[Leetcode] 2619. Array Prototype Last (Javascript) (0) | 2023.04.12 |
[Leetcode] 13. Roman to Integer (Javascript) (0) | 2023.04.11 |
[Leetcode] 66. Plus One (Javascript) (0) | 2023.04.10 |