Golang 编写一个函数来查找字符串数组中的最长公共前缀

Jackey Golang 3,408 次浏览 , 没有评论

要求

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:所有输入只包含小写字母 a-z 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix

代码

package main

import (
  "fmt"
  "strings"
)

func main() {
  strs := []string{"a"}
  fmt.Println(longestCommonPrefix(strs))
}

func longestCommonPrefix(strs []string) string {
  var res = ""
  if len(strs) == 0 {
    return ""
  }
next:
  for j := 1; j <= len(strs[0]); j++ {
    res = strs[0][:j]
    for _, v := range strs {
      if strings.HasPrefix(v, res) == false {
        if j-1 == 0 {
          res = ""
        } else {
          res = strs[0][:(j - 1)]
        }
        j = len(strs[0]) + 1
        continue next
      }
    }
  }
  return res
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go