编程珠玑column15 strings of pearls

来源:互联网 发布:39健康软件 编辑:程序博客网 时间:2024/06/14 15:58


15.2

介绍了求字符串中最长的重复子串的方法。


其中一种方法是先申请一个指针数组a保存指向该字符串中每一个字符所在的地址。


这样a中的元素依次为第0个字符,第1个字符,第2个字符.的地址...。

然后对a进行一个快速排序。这样最长的重复子串只需从a中的相邻元素中搜索。

排序耗时o(nlgn),,相邻元素之间比较计算最长重复子串耗时o(n)



15.3


word为指向字符串的后缀数组,word中的元素从每个单词的起点开始,word中存储的地址指向每个单词的词首。


after reading the input,we append k null characters (so the comparison function doesn't run off the end).

for i=[0,k)

word[nword][i]= 0 

这是在输入文本最后(最后一个单词后面)填充k个空白字符。

个人觉得只需填充一个0就可以了。因为即使文本中某一位置的单词和最后一个单词进行比较,在比较出这单词相同之后,再遇到空白字符比较也就终止了。不会再继续下去了啊(不知道理解的是不是有问题)



对于输入文本为"of the people, by the people,for the people",

word[0]指向单词0的地址,word[1]指向单词1的地址,word[n]指向单词n的地址

即word[0]指向单词of的地址

排序前

word[0]:of the people,by the people,for the people

word[1]:the people,by the people,for the people

word[2]: people, by the people,for the people

word[3]:by the people,for the people

word[4]:the people,for the people

word[5]: people,for the people

word[6]:for the people

word[7]:the people

word[8]: people


排序后:

word[0]:by the people,for the people

word[1]:for the people

word[2]:of the people,by the people,for the people

word[3]: people

word[4]: people, by the people,for the people

word[5]:people,for the people

word[6]:the people

word[7]:the people,by the people,for the people

word[8]:the people,for the people


原创粉丝点击