4.2 Expression Evaluation / Parentheses
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন
Demo: Longest Valid Parentheses — LC 32 (Hard — Google High)
Statement (Demo): Given a string s of only '(' and ')', return the length of the longest valid parentheses substring.
Example: s=")()())" → 4 | ⚡ len ≤ 3×10⁴
Approach: Keep indices on a stack with -1 at the bottom as a base. Push on (. On ) pop — if the stack is now empty, this ) becomes the new base; otherwise the current valid length is i - stack.top.
function longestValidParentheses(s) {
const stack = [-1]; // base index
let best = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === "(") stack.push(i);
else {
stack.pop();
if (stack.length === 0)
stack.push(i); // new base
else best = Math.max(best, i - stack[stack.length - 1]);
}
}
return best;
}
Complexity: Time O(n), Space O(n)
নোট · ফাঁকা
প্রবলেম
- Valid Parenthesesplan · দিন ০০৪🔥 Must-doLC 20
Statement: Given a string
sof only'(',')','{','}','[',']', return whether every bracket closes in the correct order.
Example:s="()[]{}"→true| ⚡len ≤ 10⁴নোট · ফাঁকা
- Backspace String CompareLC 844(stack, or two pointers from the back in O(1) space)
Statement: Given strings
sandtwhere#is a backspace, return whether both produce the same text when typed into an editor.
Example:s="ab#c", t="ad#c"→true(both are "ac") | ⚡len ≤ 200নোট · ফাঁকা