美文网首页
leetcode:14. Longest Common Pref

leetcode:14. Longest Common Pref

作者: 唐僧取经 | 来源:发表于2018-08-20 14:20 被阅读0次

    14. Longest Common Prefix

    Description

    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.

    Answer

    
    package main
    
    import (
        "fmt"
    )
    
    func longestCommonPrefix(strs []string) string {
        if len(strs) == 0 {
            return ""
        }
        if len(strs) == 1 {
            return strs[0]
        }
        var temp byte
        var i int
        for i = 0; i < len(strs[0]); i++ {
    
            temp = strs[0][i]
    
            for j := 0; j < len(strs); j++ {
                if len(strs[j]) == 0 {
                    return ""
                }
    
                if i < len(strs[j]) {
                    if strs[j][i] != temp {
                        return strs[0][:i]
                    }
    
                } else {
                    return strs[0][:i]
                }
            }
        }
        return strs[0][:i]
    }
    
    func main() {
        fmt.Println(longestCommonPrefix([]string{"ccc", "ccccc"}))
    }
    
    
    

    相关文章

      网友评论

          本文标题:leetcode:14. Longest Common Pref

          本文链接:https://www.haomeiwen.com/subject/kpqliftx.html