|
@@ -0,0 +1,60 @@
|
|
|
+package main
|
|
|
+
|
|
|
+import "fmt"
|
|
|
+
|
|
|
+func main() {
|
|
|
+ var strs []string
|
|
|
+
|
|
|
+ strs = []string{}
|
|
|
+ fmt.Println(longestCommonPrefix(strs))
|
|
|
+
|
|
|
+ strs = []string{"a"}
|
|
|
+ fmt.Println(longestCommonPrefix(strs))
|
|
|
+
|
|
|
+ strs = []string{"a", "b"}
|
|
|
+ fmt.Println(longestCommonPrefix(strs))
|
|
|
+
|
|
|
+ strs = []string{"flower", "flow", "flight"}
|
|
|
+ fmt.Println(longestCommonPrefix(strs))
|
|
|
+
|
|
|
+ strs = []string{"dog", "racecar", "car"}
|
|
|
+ fmt.Println(longestCommonPrefix(strs))
|
|
|
+
|
|
|
+ strs = []string{"a", "abc", "ac"}
|
|
|
+ fmt.Println(longestCommonPrefix(strs))
|
|
|
+
|
|
|
+ strs = []string{"abcdef", "abc", "ab"}
|
|
|
+ fmt.Println(longestCommonPrefix(strs))
|
|
|
+
|
|
|
+ strs = []string{"ab", "abcdef", "abc", "ab"}
|
|
|
+ fmt.Println(longestCommonPrefix(strs))
|
|
|
+}
|
|
|
+
|
|
|
+func longestCommonPrefix(strs []string) string {
|
|
|
+ var res string
|
|
|
+ var char string
|
|
|
+ var mark bool
|
|
|
+ if len(strs) == 0 {
|
|
|
+ return ""
|
|
|
+ }
|
|
|
+ for i := 0; i < len(strs[0]); i++ {
|
|
|
+ char = strs[0][i : i+1]
|
|
|
+ mark = true
|
|
|
+ for j := 0; j < len(strs); j++ {
|
|
|
+ var str = strs[j]
|
|
|
+ if i > len(str)-1 {
|
|
|
+ mark = false
|
|
|
+ break
|
|
|
+ }
|
|
|
+ if str[i:i+1] != char {
|
|
|
+ mark = false
|
|
|
+ break
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if !mark {
|
|
|
+ break
|
|
|
+ }
|
|
|
+ res += char
|
|
|
+ }
|
|
|
+ return res
|
|
|
+}
|