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"}))
}