1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// @Title: 通过删除字母匹配到字典里最长单词 (Longest Word in Dictionary through Deleting)
// @Author: 15816537946@163.com
// @Date: 2019-11-16 10:02:20
// @Runtime: 28 ms
// @Memory: 7 MB


func findLongestWord(s string, d []string) string {
	// 遍历d的每一个元素,双指针方法判断s是否为d中的一个子序列,按照单词的首个字母顺序排序
	sort.Sort(stringSlice(d))
	for i := range d {
		if isSub(s, d[i]) {
			return d[i]
		}

	}
	return ""
}

// stringSlice 实现了 sort.Interface 接口
type stringSlice []string

func (s stringSlice) Len() int { return len(s) }

/*
func (s stringSlice) Less(i, j int) bool {
	if len(s[i]) == len(s[j]) {
		return s[i] < s[j]
	}
	return len(s[i]) > len(s[j])
}
*/
func (s stringSlice) Less(i, j int ) bool {
	if len(s[i]) == len(s[j]) {
		return s[i] < s[j]
	}

	return len(s[i]) > len(s[j])
}

func (s stringSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

/*
type stringSlice []string

func (s stringSlice) Len() int { return len(s) }

func (s stringSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }


*/

func isSub(s, sub string) bool {
	if len(s) < len(sub) {
		return false
	}

	i, j := 0, 0
	for i < len(s) && j < len(sub) {
		if s[i] == sub[j] {
			j++
		}
		i++
	}
	return j == len(sub)
}