LeetCode 014 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.

简单的说就是求最长公共前缀,解法的思路如图,

LeetCode 014 Longest Common Prefix_第1张图片
image-20180708134936170

就是每两个字符串进行对比,寻找最大的前缀,然后找到的前缀与下一个字符串进行前缀匹配,当然也可以先把字符串根据长度排序,用最短的那个字符串作为最开始的前缀来进行匹配查找,因为最长公共前缀的长度不会超过最短的字符串长度~

Solution

package main

import (
    "fmt"
    "strings"
)

func longestCommonPrefix(strs []string) string {
    // 如果数组是空的,那么返回 ""
    if(len(strs) == 0) {
        return ""
    }
    // 取第一个字符串作为初始的前缀
    prefix := strs[0]
    for i := 1; i < len(strs); i++{
        // 这个循环的目的是,根据查找前缀的位置来判断是否已经找到公共前缀
        for ; strings.Index(strs[i], prefix) != 0; {
            // 没找到,则去掉最后一位,继续尝试
            prefix = prefix[0:len(prefix) - 1]
            // 如果没有公共前缀,就返回 ""
            if(len(prefix) == 0) {
                return ""
            }
        }
    }
    return prefix
}

func main() {
    a := []string{"flower", "flow", "flight"}
    fmt.Println(longestCommonPrefix(a))
    a = []string{"aa", "a"}
    fmt.Println(longestCommonPrefix(a))
}

你可能感兴趣的:(LeetCode 014 Longest Common Prefix)