String
practice
LeetCode 334 - Reverse String
LeetCode 541 - Reverse String II
LeetCode 151 - Reverse Words in a String
Notes
- revert a string twice will stay unchanged, use this trick on some sub-strings can reach some complex transformation.
String Matching (KMP)
Naive Approach
The naive approach to string matching involves comparing the pattern with the text character by character. If a mismatch is found, the pattern is shifted by one position and the comparison is repeated.
1 | int naiveSearch(string text, string pattern) { |
This approach has a time complexity of O(n * m)
in the worst case, where n
is the length of the text and m
is the length of the pattern.
The main drawback of this approach is that it does not take advantage of the information in the pattern to avoid unnecessary comparisons.
KMP Algorithm
This works because if the suffix matches, then its identical prefix should also match. Therefore, we can skip comparisons for those letters. This approach eliminates the need to backtrack the pointer for the target string and uses the pointers in the pattern and prepared information to achieve the same result.
Prepare LSP (Longest Proper Prefix which is also a suffix)
- Step 1: Initialize a LPS array of the same size as the pattern and set all array elements to -1, where
-1
denotes no LPS is recognized at the given index. - Step 2: Define two indices
j = 0
,i = 1
. - Step 3: Compare the letters at pattern[i] and pattern[j]
- match:
1
2
3LPS[i] = j
i += 1
j += 1 - mismatch:
1
2
3
4
5if (j == 0) {
i += 1
} else {
j = LPS[j - 1] + 1
}
Repeat step 3 until all the elements in the pattern are iterated.
- match:
String Matching
The process of String Matching and Building LPS array are quite similiar.
- Step 1: Define two pointers
i
,j
to denote the current index at the main string and pattern respectively. - Step 2: Compare the letters at
string[i]
andpattern[j]
- match:
1
2i += 1
j += 1 - mismatchrepeat step 2 until the whole pattern is matched or the length of unchecked in the main string is less than the length if the pattern string.
1
2
3
4
5if (j == 0) {
i += 1
} else {
j = LPS[j - 1] + 1
}
- match:
Practice
LeetCode 28 - Find the Index of the First Occurrence in a String
LeetCode 459 - Repeated Substring Pattern