String Algorithm[1]
String Algorithm[1]
Core Concept
The sliding window pattern maintains a window that can expand, or contract based on certain
conditions. It's particularly useful when you need to find a subarray or substring that meets
specific criteria.
How It Works
1. Create a window with two pointers (start, end)
2. Expand window by moving end pointer
3. Contract window by moving start pointer when needed
4. Track current window state (often using hash map/array)
Example Implementation
Problem: Find longest substring with at most k distinct characters
LeetCode 340 - Longest Substring with At Most K Distinct Characters
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
if (k == 0) return 0;
return maxLen;
}
};
Core Concept
Two pointers technique uses two pointers to traverse the string, often from opposite ends,
meeting in the middle.
How It Works
1. Initialize two pointers (usually left and right)
2. Move pointers based on conditions
3. Process elements at pointer positions
4. Continue until pointers meet or cross
Example Implementation
Problem: Check if string is palindrome ignoring non-alphanumeric characters
LeetCode 125 - Valid Palindrome
class Solution {
public:
bool isPalindrome(string s) {
int left = 0, right = s.length() - 1;
// Compare characters
if (tolower(s[left]) != tolower(s[right])) {
return false;
}
left++;
right--;
}
return true;
}
};
Core Concept
DP in strings involves building solutions using previously computed results, often using a
table to store intermediate results.
How it Works
1. Create DP table (often 2D for strings)
2. Define base cases
3. Fill table using recurrence relation
4. Extract final result
Example Implementation
Problem: Find length of longest common substring
LeetCode (Similar to 1143. Longest Common Subsequence)
class Solution {
public:
int longestCommonSubstring(string text1, string text2) {
int m = text1.length(), n = text2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
int maxLength = 0;
return maxLength;
}
};
Core Concept
Use hash tables or arrays to count character frequencies or track character positions.
How It Works
1. Create frequency map/array
2. Process string to update counts
3. Use counts to solve problem
4. Often O(n) time and space
Example Implementation
Problem: First unique character in string
LeetCode 387 - First Unique Character in a String
class Solution {
public:
int firstUniqChar(string s) {
vector<int> freq(26, 0);
vector<int> firstPos(26, -1);
How It Works
1. Initialize empty stack
2. Push opening characters
3. Pop and match with closing characters
4. Check stack state for validity
Example Implementation
Problem: Valid parentheses checking
LeetCode 20 - Valid Parentheses
class Solution {
public:
bool isValid(string s) {
stack<char> st;
unordered_map<char, char> pairs = {
{')', '('},
{']', '['},
{'}', '{'}
};
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else {
if (st.empty() || st.top() != pairs[c]) {
return false;
}
st.pop();
}
}
return st.empty();
}
};