https://leetcode.com/problems/longest-common-prefix/
Longest Common Prefix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
package main
package main
// https://leetcode.com/problems/longest-common-prefix/
import (
"strings"
)
func main() {
// strs := []string{"flower", "flow", "flight"}
strs := []string{"dog", "racecar", "car"}
longestCommonPrefix(strs)
}
//제출 코드
func longestCommonPrefix(strs []string) string {
prefix := strs[0]
for _, str := range strs {
if len(prefix) > len(str) {
prefix = str
}
}
for true {
for i, str := range strs {
if !strings.HasPrefix(str, prefix) {
prefix = prefix[:len(prefix)-1]
break
}
if i == len(strs)-1 {
return prefix
}
}
}
return prefix
}
'Algorithm > Go' 카테고리의 다른 글
[LeetCode] Adding Spaces to a String (0) | 2022.01.24 |
---|---|
[LeetCode] Maximum Subarray (0) | 2022.01.10 |
[LeetCode] Longest Substring Without Repeating Characters (0) | 2022.01.03 |
[LeetCode] Minimum Index Sum of Two Lists (0) | 2022.01.03 |
[LeetCode] Merge Two Sorted Lists (0) | 2021.12.26 |