14. 最长公共前缀

image.png

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func longestCommonPrefix(strs []string) string {
  7. if len(strs)==0 {
  8. return ""
  9. }
  10. if len(strs)==1 {
  11. return strs[0]
  12. }
  13. preStr :=strs[0]
  14. for i:=1;i<len(strs);i++{
  15. for !strings.HasPrefix(strs[i],preStr){
  16. if len(preStr)==0 {
  17. return ""
  18. }
  19. preStr =preStr[0:len(preStr)-1]
  20. }
  21. }
  22. return preStr
  23. }
  24. func main() {
  25. fmt.Println(longestCommonPrefix([]string{"flower","flow","flight"}))
  26. fmt.Println(longestCommonPrefix([]string{"dog","racecar","car"}))
  27. }