如何定位给定字符串中缺失的大括号的索引位置?
Fixing Missing Brace Detection with Index Tracking
Hey there! Let's tackle this brace matching problem together. I see you tried using two arrays to track opening and closing braces, but couldn't pinpoint where the missing or extra ones are. Using a stack is the classic approach here—it not only tells you if the string is valid but also lets you find the exact positions of unmatched braces.
How the Stack Approach Works
Instead of storing the brace characters themselves, we'll store the indices of opening braces in a stack. Here's the step-by-step logic:
- When we encounter a
{, push its index onto the stack (we need to remember where it is if it doesn't get matched). - When we encounter a
}:- If the stack isn't empty, pop the top index—this means we found a matching pair of braces.
- If the stack is empty, this
}has no corresponding{, so we record its index as an extra closing brace.
- After traversing the entire string, any indices left in the stack are
{characters that never got a matching}—these are the ones missing a closing brace.
Implementation Code (JavaScript)
function findMissingBraces(str) { const openingStack = []; const extraClosingIndices = []; const missingClosingIndices = []; for (let idx = 0; idx < str.length; idx++) { const char = str[idx]; if (char === '{') { openingStack.push(idx); } else if (char === '}') { if (openingStack.length > 0) { openingStack.pop(); } else { extraClosingIndices.push(idx); } } // Ignore other characters (spaces, comments, variables, etc.) } // Remaining entries in the stack are opening braces without matches missingClosingIndices.push(...openingStack); return { isStringValid: missingClosingIndices.length === 0 && extraClosingIndices.length === 0, openingBracesMissingClosing: missingClosingIndices, extraClosingBraces: extraClosingIndices }; } // Test your sample inputs const validInput = `{ { { } } } { } { { } }`; console.log(findMissingBraces(validInput)); // Output: { isStringValid: true, openingBracesMissingClosing: [], extraClosingBraces: [] } const invalidInput = ` { { } } { //missing a closing brace here { } `; const result = findMissingBraces(invalidInput); console.log("Is valid?", result.isStringValid); console.log("Opening braces missing closing at indices:", result.openingBracesMissingClosing); console.log("Extra closing braces at indices:", result.extraClosingBraces);
What This Solves
- You'll get clear feedback on exactly where the problem is:
openingBracesMissingClosinggives you the indices of{that need a corresponding}.extraClosingBracesgives you indices of}that have no matching{.
- Unlike your original array approach, this ties each unmatched brace directly to its position in the string, making it easy to debug.
内容的提问来源于stack exchange,提问作者Deepak




