[LeetCode]14. Longest Common Prefix

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: ["flower","flow","flight"]
Output: "fl"

Example 2:

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

Note:

All given inputs are in lowercase letters a-z.

Analyse:

找出陣列所有string中最長的共同prefix.

依序兩兩相比並記錄prefix.

Solution:

class Solution {
    
    func longestCommonPrefix(_ strs: [String]) -> String {
       if(strs.count == 0) {
           return "";
       }
        
       var output = strs[0];
       
       for i in 1..<strs.count {
           output = findCommonPrefix(output, strs[i]);
       }
        
       return output;  
    }
    
    func findCommonPrefix(_ str1: String, _ str2: String) -> String {
        let chars1 = Array(str1)
        let chars2 = Array(str2)
        var output = "";
        
        var i = 0;
        
        while(i < chars1.count && i < chars2.count && chars1[i] == chars2[i]) {
            output = output + String(chars1[i]);
            i += 1;
        }
        
        return output;  
    }
}  

Solution 2:

class Solution {
    func longestCommonPrefix(_ strs: [String]) -> String {
        var minLength = strs.count == 0 ? 0 : Int.max
        var list: [[Character]] = []
        var output = ""
        
        for i in 0..<strs.count {
            let chars = Array(strs[i])
            list.append(chars)
            
            if(chars.count < minLength) {
                minLength = chars.count
            }
        }
      
        for i in 0..<minLength {
            for j in 0..<list.count {

                if(list[j][i] != list[0][i]) {
                    return output
                } 
            }
            output = output + String(list[0][i])
        }

        return output    
    }
}

Last updated