본문 바로가기
LeetCode

[LeetCode] 14. Longest Common Prefix

by JungSeung 2023. 10. 20.
728x90

https://leetcode.com/

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","flight"]
Output: "fl"

 

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.


Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

 

Code :

/*
	1. 만약 strs의 길이가 0이라면, 빈 문자열을 반환합니다.
	2. strs[0]의 각 문자열에 대해 접두사를 찾습니다.
	3. 만약 현재 인덱스 i에서 strs[0][i]와 s[i]가 다르다면, 현재까지의 문자열을 반환합니다.
	4. 모든 반복이 완료되면 strs[0]을 반환합니다.
*/
var longestCommonPrefix = function(strs) {
    if(!strs.length) return '';
    
    for(let i = 0; i < strs[0].length; i++) { // i = f, l, o, w, e, r
        for(let s of strs) { // s = flower, flow, flight
            if(s[i] !== strs[0][i]) {
                return s.slice(0, i);
            }
        }
    }   
    return strs[0];
};

 

Solutions Code :

/*
	1. 만약 strs의 길이가 0이라면, 빈 문자열을 반환합니다.
	2. ans를 strs의 첫 번째 문자열로 초기화합니다.
	3. strs의 각 문자열에 대해 ans가 현재 문자열의 접두사인지 확인합니다. 만약 그렇지 않다면, ans를 하나씩 줄여나가며 검사합니다.
	4. ans가 빈 문자열이 되면 빈 문자열을 반환합니다.
	5. 모든 검사가 완료되면 ans를 반환합니다.
*/
var longestCommonPrefix = function(strs) {
    if (strs.length === 0) {
        return '';
    }
    let ans = strs[0];
    for (let i = 1; i < strs.length; i++) {
        while (strs[i].indexOf(ans) !== 0) {
            ans = ans.substring(0, ans.length - 1);
            if (ans === '') {
                return '';
            }
        }
    }
    return ans;
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 16. 3Sum Closest  (0) 2023.10.23
[LeetCode] 15. 3Sum  (0) 2023.10.20
[LeetCode] 13. Roman to Integer  (2) 2023.10.19
[LeetCode] 12. Integer to Roman  (0) 2023.10.19
[LeetCode] 11. Container With Most Water  (0) 2023.10.18