Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

exercises(matching-brackets): example: avoid using allocator #338

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions exercises/practice/matching-brackets/.meta/example.zig
Original file line number Diff line number Diff line change
@@ -1,20 +1,34 @@
const std = @import("std");
const mem = std.mem;

fn toClosing(c: u8) u8 {
return switch (c) {
'(' => ')',
'[' => ']',
'{' => '}',
else => unreachable,
};
}

/// Returns whether the characters `(`, `[`, and `{` are matched and correctly nested in `s`.
pub fn isBalanced(allocator: mem.Allocator, s: []const u8) mem.Allocator.Error!bool {
var stack = std.ArrayList(u8).init(allocator);
defer stack.deinit();
/// Caller guarantees that the nesting depth of those characters in `s` is at most 100.
// The tests use `try`, so this function returns `!bool` even though it cannot return an error.
pub fn isBalanced(_: mem.Allocator, s: []const u8) !bool {
var stack: [100]u8 = undefined;
var i: usize = 0;

for (s) |c| {
switch (c) {
'(', '[', '{' => try stack.append(c),
')' => if (stack.items.len == 0 or stack.pop() != '(') return false,
']' => if (stack.items.len == 0 or stack.pop() != '[') return false,
'}' => if (stack.items.len == 0 or stack.pop() != '{') return false,
'(', '[', '{' => {
stack[i] = toClosing(c);
i += 1;
},
')', ']', '}' => {
if (i > 0 and stack[i - 1] == c) i -= 1 else return false;
},
else => continue,
}
}

return stack.items.len == 0;
return i == 0;
}