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""
.
Input: strs = ["flower","flow","flight"]
Output: "fl"
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
consists of only lowercase English letters.var longestCommonPrefix = function (strs) {
for (let i = 0; i < strs[0].length; i++) {
for (let j of strs) {
if (j[i] != strs[0][i]) {
return j.slice(0, i);
}
}
}
return strs[0];
};
strs 배열의 첫번째 단어를 기준으로 배열내 단어들을 비교하면서 다른 문자가 생기면 그 전까지 slice 메서드를 통해 return 하고 만약 모두 같으면 기준이 된 단어를 return하도록 했다.