aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorterminaldweller <devi@terminaldweller.com>2025-09-16 02:08:31 +0000
committerterminaldweller <devi@terminaldweller.com>2025-09-16 02:08:31 +0000
commit18fed346fbfab722d8ce9992242ff9c0fbec7b59 (patch)
treecff5f711f85cb0024473fc0846753e1cb1fd9d38
parent1239 (diff)
downloadleetcode-18fed346fbfab722d8ce9992242ff9c0fbec7b59.tar.gz
leetcode-18fed346fbfab722d8ce9992242ff9c0fbec7b59.zip
14
-rw-r--r--14/main.go40
1 files changed, 40 insertions, 0 deletions
diff --git a/14/main.go b/14/main.go
new file mode 100644
index 0000000..f22304a
--- /dev/null
+++ b/14/main.go
@@ -0,0 +1,40 @@
+package main
+
+import "fmt"
+
+func longestCommonPrefix(strs []string) string {
+ longestPrefix := strs[0]
+ for _, element := range strs {
+ for index, char := range element {
+ if len(longestPrefix) == 0 {
+ break
+ }
+ if index > len(longestPrefix)-1 {
+ // longestPrefix = longestPrefix[0 : index-1]
+ // fmt.Println("XXX:", longestPrefix)
+ break
+ }
+ if byte(char) != longestPrefix[index] {
+ longestPrefix = longestPrefix[0:index]
+ }
+ }
+
+ if len(longestPrefix) > len(element) {
+ longestPrefix = longestPrefix[0:len(element)]
+ }
+ // fmt.Println(longestPrefix)
+ }
+
+ return longestPrefix
+}
+
+func main() {
+ strs := []string{"flower", "flow", "flight"}
+ fmt.Println(longestCommonPrefix(strs))
+ strs2 := []string{"dog", "racecar", "car"}
+ fmt.Println(longestCommonPrefix(strs2))
+ strs3 := []string{"ab", "a"}
+ fmt.Println(longestCommonPrefix(strs3))
+ strs4 := []string{"aaa", "aa", "aaa"}
+ fmt.Println(longestCommonPrefix(strs4))
+}