0. 문제
https://leetcode.com/problems/longest-common-prefix/submissions/
Longest Common Prefix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문자열 배열 중에서 가장 긴 공통 접두사 문자열을 찾는 함수를 작성하기
공통 접두사가 없으면 빈 문자열을 반환
#1
Input: strs = ["flower","flow","flight"]
Output: "fl"
#2
Input: strs = ["dog","racecar","car"]
Output: ""
1.언어
자바스크립트(JavaScript)
2. 문제 풀이
var longestCommonPrefix = function(strs) {
let result="";
if (strs.length < 2) return strs[0]; // 입력이 1이하면 그대로 출력
for (let i=0; i<strs[0].length; i++){
for (let j=1; j<strs.length; j++){
if (strs[0][i] !== strs[j][i]) return result;
}
result += strs[0][i];
}
return result; // 모든 입력이 같을 시
};
Runtime: 81 ms, faster than 71.58% of JavaScript online submissions for Longest Common Prefix.
Memory Usage: 43.1 MB, less than 31.09% of JavaScript online submissions for Longest Common Prefix.
첫 문자열을 다른 문자열과 앞에서부터 하나씩 검사하는 코드
리트코드는 런타임 퍼센트가 나와서 상위 답이 나올 때 까지 효율적이게 연습하도록 도와주는 거 같다.
'LeetCode > 코딩 테스트 스터디 1주차' 카테고리의 다른 글
[LeetCode] 3. Longest Substring Without Repeating Characters 풀이 (0) | 2022.07.10 |
---|---|
[LeetCode] 2. Add Two Numbers 풀이 (0) | 2022.07.10 |
[LeetCode] 13. Roman to Integer 풀이 (0) | 2022.07.10 |
[LeetCode] 9. Palindrome-Number 풀이 (0) | 2022.07.10 |
[LeetCode] 1. Two Sum 풀이 (0) | 2022.07.10 |