문제
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.
https://leetcode.com/problems/longest-common-prefix
풀이
substring 결과를 각 문자열의 시작과 동일한지 비교했다.
첫 문자열에서 substring을 늘려가면서 하기에는 이후에 다시 줄여야할 수 있기에, 처음부터 줄여가면서 비교하는 방식으로 진행했다.
긴 문자들만 나온다면 아예 정렬해놓고 처음 문자열과 마지막 문자열을 각 자리별로 비교하는 형태도 괜찮을 것 같다.
코드
class Solution {
public String longestCommonPrefix(String[] strs) {
for(int i = strs[0].length(); i > 0; i--) {
int f_cnt = 0;
for(int j = 0; j < strs.length; j++) {
if(strs[j].startsWith(strs[0].substring(0, i))) {
f_cnt++;
if(f_cnt == strs.length) {
return strs[0].substring(0, i);
}
} else {
break;
}
}
}
return "";
}
}
결과
Runtime : 2 ms
Memory Usage : 44.08 MB
'LeetCode' 카테고리의 다른 글
16. 3Sum Closest (0) | 2025.01.09 |
---|---|
15. 3Sum (0) | 2025.01.07 |
13. Roman to Integer (1) | 2024.12.20 |
12. Integer to Roman (0) | 2024.11.30 |
11. Container With Most Water (0) | 2024.11.24 |