14.go 534 B

123456789101112131415161718192021222324252627282930
  1. package main
  2. func longestCommonPrefix(strs []string) string {
  3. res := make([]rune, 0)
  4. // spacial case
  5. if len(res) == 0 {
  6. return ""
  7. }
  8. cnt := len(strs[0])
  9. // find minimum length of strings
  10. for _, v := range strs {
  11. if cnt > len(v) {
  12. cnt = len(v)
  13. }
  14. }
  15. // vertical serach
  16. // [0 _] [0 _] [0 _] --> [_ 1] [_ 1] [_ 0] --> [0]
  17. for i := 0; i < cnt; i++ {
  18. curr := strs[0][i]
  19. for _, v := range strs {
  20. if curr != v[i] {
  21. cnt = -1
  22. }
  23. }
  24. if cnt != -1 {
  25. res = append(res, rune(curr))
  26. }
  27. }
  28. return string(res)
  29. }