forked from pro648/BasicDemos-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContents.swift
More file actions
52 lines (44 loc) · 1.23 KB
/
Copy pathContents.swift
File metadata and controls
52 lines (44 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import UIKit
example(of: "Using a stack") {
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
print(stack)
if let poppedValue = stack.pop() {
assert(4 == poppedValue)
print("Popped: \(poppedValue)")
}
}
example(of: "Initializing a stack from an array") {
let array = ["A", "B", "C", "D"]
var stack = Stack(array)
print(stack)
stack.pop()
}
example(of: "Initializing a stack from an array literal") {
var stack: Stack = [1.0, 2.0, 3.0, 4.0]
print(stack)
stack.pop()
}
// 查看圆扣号是否匹配
func checkParentheses(_ string: String) -> Bool {
var stack = Stack<Character>()
for character in string {
if character == "(" {
// 遇到左括号,添加到栈。
stack.push(character)
} else if character == ")" {
if stack.isEmpty {
// 遇到右括号时,如果栈是空的,则不匹配。
return false
} else {
// 不是空的,移除一个元素。
stack.pop()
}
}
}
// 最终,栈是空的,就刚好匹配;否则,不匹配。
return stack.isEmpty
}