0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LeetCode 【#14 Longest Common Prefix】のGo言語解法

Posted at

概要

問題詳細

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:

0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.

解説

要件

文字列の配列で一番長いの共通の接頭辞を探し出すの要件です。
まとめることは、
1, 接頭辞
2, 共通
3, 一番長い

解法

一番簡単な状況をまとめます

func longestCommonPrefix(strs []string) string {
  size := len(strs)
  if size == 0 {
    return ""
  }
  if size == 1 {
    return strs[0]
  }
  ...
}

Goで接頭辞の判断

strings.HasPrefix(str1, str2)

ref: https://golang.org/pkg/strings/#HasPrefix

変数の初期化

common := strs[0]
length := len(common)
result := ""

要件によって、結果は最初の文字列にも必ず含まれているので、まず頭の文字列を選択します。
結果変数はまず空に初期化する。

接頭辞の循環

for j := 1; j <= length; j++ {
  current := common[0:j]
  ...
}

接頭辞の長さは頭の文字列の長さに限られているので、上記の循環を設計しました。

配列の循環

for k := 1; k < size; k++ {
  ...
}

接頭辞を判断する

for k := 1; k < size; k++ {
  if !strings.HasPrefix(strs[k], current) {
    break
  }
  ...
}

接頭辞の判断がfalseの場合は、循環を中止します。

for k := 1; k < size; k++ {
  if !strings.HasPrefix(strs[k], current) {
    break
  }
  if (k == size && len(result) < len(current)) {
    result = current
  }
}
  • k == size の判定がtrueの場合は、今の接頭辞currentが共通と判断する認識です。
  • len(result) < len(current) の判定がtrueの場合は、今の接頭辞currentが一番長いと判断する認識です。

成果物

func longestCommonPrefix(strs []string) string {
  size := len(strs)
  if size == 0 {
    return ""
  }
  if size == 1 {
    return strs[0]
  }
  common := strs[0]
  length := len(common)
  result := ""
  for j := 1; j <= length; j++ {
    current := common[0:j]

    var k int
    for k = 1; k < size; k++ {
      if !strings.HasPrefix(strs[k], current) {
        break
      }
    }
    if (k == size && len(result) < len(current)) {
      result = current
    }
  }

  return result
}

submit結果

image.png

結論

接頭辞の制限があるので、難易度は低くなると思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?