JavaScript实现对应位置{}分别存储至ys、ns数组的算法需求
How to Map Matching Braces to Corresponding Indices in Two Arrays in JavaScript
Got it, let's tackle this problem. The core idea here is using a stack to track the positions of opening braces so we can correctly pair each closing brace with its match and place them at the same index in both arrays.
Here's how it works step by step:
- We loop through each character in the input string once.
- Whenever we see an opening brace
{, we add it to theysarray and push its index inysonto a stack—this stack keeps track of which opening braces are still waiting for their closing counterparts. - When we hit a closing brace
}, we pop the top index from the stack (this tells us exactly which opening brace it matches) and put the closing brace at that index in thensarray. - By the end, every index
iwill hold a matching pair:ys[i]is the opening brace,ns[i]is its corresponding closing brace.
Let's turn this into working JavaScript code:
function mapMatchingBraces(inputStr) { const ys = []; const ns = []; const stack = []; for (const char of inputStr) { if (char === '{') { ys.push(char); // Push the index of this new opening brace in ys to the stack stack.push(ys.length - 1); } else if (char === '}') { // Handle cases where there's no matching opening brace if (stack.length === 0) { console.warn("Found an unbalanced closing brace—ignoring it"); continue; } const matchingIndex = stack.pop(); ns[matchingIndex] = char; } // All other characters are ignored since we only care about braces } // Check if there are any unclosed opening braces left if (stack.length > 0) { console.warn(`${stack.length} opening braces were never closed`); } return { ys, ns }; }
Let's test this with your sample inputs to make sure it works:
Example 1: "- a{1}b{1}c{1}"
const result1 = mapMatchingBraces("- a{1}b{1}c{1}"); console.log(result1.ys); // Output: ['{', '{', '{'] console.log(result1.ns); // Output: ['}', '}', '}'] // Each index i has a perfectly matched pair: ys[i] ↔ ns[i]
Example 2: "- a{a{1}b{1}c{1}}"
const result2 = mapMatchingBraces("- a{a{1}b{1}c{1}}"); console.log(result2.ys); // Output: ['{', '{', '{', '{'] console.log(result2.ns); // Output: ['}', '}', '}', '}'] // The outer braces are at index 0 in both arrays, and each inner pair lines up correctly too.
Example 3: "- a{a{a{1}b{1}}b{b{1}c{1}}d{1}}"
After running this through the function, ys will contain 8 opening braces, and ns will have 8 closing braces—each at the exact index of their matching opening brace.
A few extra points to note:
- The code includes basic error handling for unbalanced braces (it'll warn you in the console if there are more opening or closing braces than the other).
- Non-brace characters are completely ignored, which is exactly what we need for your input format.
- This runs in O(n) time (where n is the length of the input string) since each character is processed once, and stack operations are constant time.
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

