Balanced Brackets II
Difficulty: Medium · Topics: Stack, Parsing
Difficulty: Medium | Tags: Stack, Parsing
Description
Given a string representing Java source code, check if all brackets ({}, (), []) are properly matched and nested. Brackets inside string literals ("..."), character literals ('x'), line comments (//), and block comments (/* ... */) must be ignored.
Implement:
isBalanced(String sourceCode) → boolean
Return true if all brackets in the actual code (excluding strings, char literals, and comments) are properly matched.
Examples
Example 1 — Bracket inside string:
Input: "String s = \"}\"; if (true) { }"
Output: true
Explanation: The } inside the string literal is ignored.
Example 2 — Bracket in comment:
Input: "// { in comment\nint x = (1 + 2);"
Output: true
Explanation: The { in the line comment is ignored.
Example 3 — Unbalanced code:
Input: "public void foo() { if (true) { }"
Output: false
Explanation: Missing one closing brace for the method body.
Example 4 — Char literal:
Input: "char c = '{'; int[] arr = new int[5];"
Output: true
Explanation: The { inside the char literal is ignored.
Constraints
- Brackets inside string literals, character literals, and comments must be ignored.
- Handle escape sequences in strings and char literals (
\",\',\\). - Source code length ≤ 106.
Hints
Hint 1
Build a lexer that tracks whether you're inside a string, char literal, line comment, or block comment.
Hint 2
Only push/pop brackets when in "normal code" mode — not inside any literal or comment.