TIL5.LeetCode_Longest Common Prefix

chloe·2021년 7월 31일
0

TIL

목록 보기
73/81
post-thumbnail

Write a function to find the longest common prefix string amongsts an array of strings.
If there is no common prefix, return an empty string "".

Example1:
Input:strs=["flower","flow","flight"]
Output:"fl"

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

let's check the below example answer.
I've seen quite a lot of the examples. I think below answer is the easiest one to understand.
The first thing that I should consider is that strs is an array.

var longestCommonPrefix= function(strs) {
let prefix=''
if(strs ===null || strs.length===0) return prefix;
  for(let i=0; i<strs[0].length; i++){
    const char=strs[0][i];
    // loop through all characters of the very first thing.
    for(let j=1; j<strs.length; j++){
      //loop through all other strings in the array
      if(strs[j][i] !==char) return prefix
    }
    prefix=prefix+char
  }
};

참고 :https://dev.to/urfan/leetcode-longest-common-prefix-with-javascript-32ca

profile
Front-end Developer 👩🏻‍💻

0개의 댓글