Suffix array是解決string search問題的一個工具,它是一個字串所有後綴的排序。
線性時間的構建算法主要有Kärkkäinen-Sanders(1)、Ko-Aluru(2)、KSP三種,其中KSP算法使用了類似suffix
tree的構建方式,Kärkkäinen-Sanders算法時間複雜度的遞推式爲
按照3的註記,借鑑4對LMS substring遞歸排序使用的方法, 對原始的Ko-Aluru算法進行改動以簡化內存使用和提升性能。 我的實現在字串和suffix array外僅使用兩個數組:計數排序使用的桶和一個表示L/S類型的數組, 反映了Ko-Aluru算法能達到和5同等的精簡內存佔用。
Ka-Aluru suffix array construction algorithm
規定
令字符集爲
並結合以上兩種分類定義:
對於
根據
根據6的induced sorting,只要確定了
下面考慮如何遞歸求出
定義L-substring爲夾在相鄰兩個L(-)類型字符間的子串。
定義S-substring爲夾在相鄰兩個S(+)類型字符間的子串。 定義一個L-substring
對於兩個長度不同的L-substring
先用桶排序求出所有L類型字符的大小,使用一次induced
sorting根據L計算S,這樣便得到了所有形如
實現技巧
整個實現分爲幾個階段,仍然設
- 計算
數組,需要使用 - 使用兩次induced sorting計算L-substring的大小,需要使用
- 根據L-substring構建新字串遞歸計算子suffix array
- 根據子suffix array計算
部分的suffix array - 使用induced sorting根據
部分的suffix array得到整體suffix array
其中第2、3步需要特別注意,使用了很多技巧來節省空間佔用。比如新串的長度不大於sa[]數組的空間,遞歸調用後對sa[]進行原地操作進行位置變換。
注意到
多數文獻都在
爲L,因爲把哨兵字符看作字典序最小。 - 根據S-substring計算L-substring的induced sorting過程提前把
放入桶中。否則因爲它是最後一個字符,無法被放入桶中,當該字符的桶包含兩個或更多元素時可能會導致它的位置被覆蓋而出錯。 - 計算新字符集時,需要注意比較過程中到達邊界的情況。
Ko-Aluru算法的僞代碼如下:
1 | fn ka S sa n |
實現
C++:
1 |
|
OCaml:
1 | module KoAluru = struct |
參考文獻
Juha Kärkkäinen and Peter Sanders. “Simple Linear Work Suffix Array Construction”. English. In: Automata, Languages and Programming. Ed. by JosC.M. Baeten et al. Vol. 2719. Lecture Notes in Computer Science. Springer Berlin Heidelberg, 2003, pp. 943–955. isbn: 978-3-540-40493-4. doi: 10.1007/3-540-45061-0_73. url: http://dx.doi.org/10.1007/3-540-45061-0_73.↩︎
Pang Ko and Srinivas Aluru. “Space efficient linear time construction of suffix arrays”. In: Journal of Discrete Algorithms. Springer, 2003, pp. 200–210.↩︎
YANG Zhe. Suffix Array Construction: KA's algorithm and Induced Sorting, which is faster? 2012. url: http://yangzhe1990.wordpress.com/2012/11/04/ka-and-induced-sortingwhich-is-faster/.↩︎
Ge Nong, Sen Zhang, and Wai Hong Chan. “Two Efficient Algorithms for Linear Time Suffix Array Construction”. In: IEEE Transactions on Computers 60.10 (2011), pp. 1471–1484. issn: 0018-9340. doi: http://doi.ieeecomputersociety.org/10.1109/TC.2010.188.↩︎
Ge Nong, Sen Zhang, and Wai Hong Chan. “Two Efficient Algorithms for Linear Time Suffix Array Construction”. In: IEEE Transactions on Computers 60.10 (2011), pp. 1471–1484. issn: 0018-9340. doi: http://doi.ieeecomputersociety.org/10.1109/TC.2010.188.↩︎
Pang Ko and Srinivas Aluru. “Space efficient linear time construction of suffix arrays”. In: Journal of Discrete Algorithms. Springer, 2003, pp. 200–210.↩︎
Pang Ko and Srinivas Aluru. “Space efficient linear time construction of suffix arrays”. In: Journal of Discrete Algorithms. Springer, 2003, pp. 200–210.↩︎
Ge Nong, Sen Zhang, and Wai Hong Chan. “Two Efficient Algorithms for Linear Time Suffix Array Construction”. In: IEEE Transactions on Computers 60.10 (2011), pp. 1471–1484. issn: 0018-9340. doi: http://doi.ieeecomputersociety.org/10.1109/TC.2010.188.↩︎