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:
- 0 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lower-case English letters.
class Solution {
public String longestCommonPrefix(String[] strs) {
int len = strs.length;
if(len == 0){
return "";
}
String cmp = strs[0];
for(int i=1; i<len; i++){
int l1 = cmp.length();
int l2 = strs[i].length();
int idx = 0;
while(idx < Math.min(l1, l2)){
if(cmp.charAt(idx) != strs[i].charAt(idx)){
break;
}
idx++;
}
if(idx < l1){
cmp = cmp.substring(0,idx);
}
}
return cmp;
}
}
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 36] Valid Sudoku (0) | 2020.11.13 |
---|---|
[leetcode 29] Divide Two Integers (0) | 2020.11.13 |
[leetcode 34] Find First and Last Position of Element in Sorted Array (0) | 2020.11.12 |
[leetcode 23] Merge k Sorted Lists (0) | 2020.11.12 |
[leetcode 54] Spiral Matrix (0) | 2020.11.10 |
댓글