524.longest-word-in-dictionary-through-deleting.go 664 B

12345678910111213141516171819202122232425262728293031323334
  1. type strslice []string
  2. func (ss strslice) Len() int { return len(ss) }
  3. func (ss strslice) Less(i, j int) bool {
  4. if m, n := len(ss[i]), len(ss[j]); m != n {
  5. return n < m
  6. }
  7. return ss[i] < ss[j]
  8. }
  9. func (ss strslice) Swap(i, j int) { ss[i], ss[j] = ss[j], ss[i] }
  10. func findLongestWord(s string, d []string) string {
  11. sort.Sort(strslice(d))
  12. for i := range d {
  13. if isSubstr(s, d[i]) {
  14. return d[i]
  15. }
  16. }
  17. return ""
  18. }
  19. func isSubstr(s, t string) bool {
  20. i, j, m, n := 0, 0, len(s), len(t)
  21. if m < n {
  22. return false
  23. }
  24. s1, s2 := []rune(s), []rune(t)
  25. for ; i < m && j < n; j++ {
  26. for ; i < m && s1[i] != s2[j]; i++ {
  27. }
  28. i++
  29. }
  30. return i <= m && j == n
  31. }