From 7cd0cf6565b295ff037d1402fe5a99e144eaa068 Mon Sep 17 00:00:00 2001 From: keyansheng <65121402+keyansheng@users.noreply.github.com> Date: Tue, 8 Apr 2025 00:10:50 +0800 Subject: [PATCH 1/2] Add std::string constructor to SuffixArray --- ch6/sa_lcp.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ch6/sa_lcp.cpp b/ch6/sa_lcp.cpp index 09fccdc..0201ae1 100644 --- a/ch6/sa_lcp.cpp +++ b/ch6/sa_lcp.cpp @@ -73,6 +73,11 @@ class SuffixArray { computeLCP(); // O(n) } + SuffixArray(const string& initialT) : T(initialT.c_str()), n((int)initialT.length()) { + constructSA(); // O(n log n) + computeLCP(); // O(n) + } + ii stringMatching(const char *P) { // in O(m log n) int m = (int)strlen(P); // usually, m < n int lo = 0, hi = n-1; // range = [0..n-1] From d9692e3ae4ae0c0f3e2f846d0cf35916518f56f7 Mon Sep 17 00:00:00 2001 From: keyansheng <65121402+keyansheng@users.noreply.github.com> Date: Tue, 8 Apr 2025 10:48:46 +0800 Subject: [PATCH 2/2] Remove const from std::string constructor A const lvalue reference (const string& initialT) allows an rvalue reference (initialT + "$") to be passed in, which is now "owned" by SuffixArray and gets destructed after the SuffixArray constructor exits. By removing const, only an lvalue reference can be passed in, which is not "owned" by SuffixArray and does not get destructed after the SuffixArray constructor exits. Attempting to pass initialT + "$" to the constructor now results in a compile-time error, which is good since creating a copy is a bad idea anyway. Instead, you can initialT.push_back('$') before calling the constructor, similar to how the original char* constructor works. --- ch6/sa_lcp.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ch6/sa_lcp.cpp b/ch6/sa_lcp.cpp index 0201ae1..13e7083 100644 --- a/ch6/sa_lcp.cpp +++ b/ch6/sa_lcp.cpp @@ -73,7 +73,7 @@ class SuffixArray { computeLCP(); // O(n) } - SuffixArray(const string& initialT) : T(initialT.c_str()), n((int)initialT.length()) { + SuffixArray(string& initialT) : T(initialT.c_str()), n((int)initialT.length()) { constructSA(); // O(n log n) computeLCP(); // O(n) }