Leetcode - Easy - 14. Longest Common Prefix - Javascript

2022年1月23日 星期日

Leetcode - Easy - 14. Longest Common Prefix - Javascript


14. Longest Common Prefix

Easy

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 lower-case English letters.



解題方向:
1. 這題主要有兩種方式
    a. 先找出所有字串最少字數, 再透過 for loop 找尋所有對應的字串 prefix 是否一致
    b. 透過遍歷所有字串, 一一比對相同的 prefix, 這邊也是透過這個方式處理

程式碼 :
/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    result = ''
    
    let index = 0;
    const strsLen = strs.length;
    
    while(true) {
        let isCommon = true;
        const firstChat = strs[0][index];
    
        for (let i =0; i<strsLen; i++) {
            const currentChat = strs[i][index];
            if (!strs[i][index] || firstChat !== currentChat) {
                return result;
            }
            
        }
        
        result += firstChat;
        index++;
    } 
    return result;
};



執行成果:


0 意見 :

張貼留言