Skip to content

Commit

Permalink
Create longest-common-prefix.md
Browse files Browse the repository at this point in the history
  • Loading branch information
LinuxSuRen authored Jan 25, 2024
1 parent 471b085 commit c59f177
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions items/longest-common-prefix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
rank: 1
description:
link:
---

```golang
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
} else if len(strs) == 1 {
return strs[0]
}

lastIndex := -1
var breakLoop bool
for i, c := range strs[0] {
for j := 1; j < len(strs); j++ {
if i + 1 > len(strs[j]) {
breakLoop = true
break
}

if c != rune(strs[j][i]) {
breakLoop = true
break
}
}

if breakLoop {
break
}
lastIndex = i
}
if lastIndex == -1 {
return ""
}
return strs[0][0: lastIndex + 1]
}
```

0 comments on commit c59f177

Please sign in to comment.