Skip to content

Instantly share code, notes, and snippets.

@SwiftArchitect
Last active March 29, 2018 01:55
Show Gist options
  • Save SwiftArchitect/334026e518d647375aa71a4430476075 to your computer and use it in GitHub Desktop.
Save SwiftArchitect/334026e518d647375aa71a4430476075 to your computer and use it in GitHub Desktop.
Swift Xcode implementation of InterviewCake _Matching Braces_ in generally O(1) time and O(n) space. ⚠️ Spoiler alert: this is an improved answer to the https://www.interviewcake.com/question/swift/bracket-validator, so no peeking!
static func properlyNested(string: String) -> Bool {
let openersToClosers:[Character:Character] = ["{":"}",
"[":"]",
"(":")"]
let closers = openersToClosers.values
var stack = [Character]()
for character in string {
if let complement = openersToClosers[character] {
stack.append(complement)
} else if closers.contains(character) {
if stack.popLast() != character {
return false
}
}
}
return stack.isEmpty
}
//
// Copyright © 2018 Xavier Schott
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
class BracesTests: XCTestCase {
func testNestedParenthesisYes() {
XCTAssertTrue(Braces.properlyNested(string: "{ [ ] ( ) }"))
}
func testNestedParenthesisNo() {
XCTAssertFalse(Braces.properlyNested(string: "{ [ ( ] ) }"))
}
func testNestedParenthesisWrong() {
XCTAssertTrue(Braces.properlyNested(string: ""))
}
}
//
// Copyright © 2018 Xavier Schott
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@SwiftArchitect
Copy link
Author

While the general idea is identical to the solution presented here, it capitalizes upon this other answer as well.

Namely, instead of pushing the opening character onto the stack, we push the corresponding closing one. This makes the algorithm simpler in a number of ways:

  • the matching closing character is fetched at no extra cost as a natural result of the existence of the opening bracket
  • since the closing character is the very character popped from the stack, it does not require another dictionary comparison
  • there is no need to verify the emptiness of the stack within the loop

This changes are not trivial since they shorten the number of operations to be performed in the inner loop. It doesn't affect the order of the algorithm, still O(n) in both size and space, but performs at least 15% faster.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment