算法系列:数组
题目1:232.用栈实现队列
思路: 自己还是没想出来,思路有些固化, 多看看理解理解。
形象的示意:
用进出栈的形式,刚好将进栈里面的元素颠倒放进出栈里, 出栈 要取出元素的时候, 就正好达成先进先出的效果。
class MyQueue {
var inStack = [Int]()
var outStack = [Int]()
init() { }
func push(_ x: Int) {
inStack.append(x)
}
func pop() -> Int {
if outStack.isEmpty {
while let item = inStack.last {
outStack.append(item)
inStack.removeLast()
}
}
return outStack.removeLast()
}
func peek() -> Int {
let head = pop()
outStack.append(head)
return head
}
func empty() -> Bool {
inStack.isEmpty && outStack.isEmpty
}
}
题目2:225. 用队列实现栈
上道题 这道题 这两道题得记一下, 没想出来。
// @lc code=start
class MyQueue {
var inStack = [Int]()
var outStack = [Int]()
init() { }
func push(_ x: Int) {
inStack.append(x)
}
func pop() -> Int {
if outStack.isEmpty {
while let item = inStack.last {
outStack.append(item)
inStack.removeLast()
}
}
return outStack.removeLast()
}
func peek() -> Int {
let head = pop()
outStack.append(head)
return head
}
func empty() -> Bool {
inStack.isEmpty && outStack.isEmpty
}
func size() -> Int {
inStack.count + outStack.count
}
}
class MyStack {
var queue = MyQueue()
init() {
}
func push(_ x: Int) {
queue.push(x)
}
func pop() -> Int {
for _ in 0..<queue.size() - 1 {
queue.push(queue.pop())
}
return queue.pop()
}
func top() -> Int {
for _ in 0..<queue.size() - 1 {
queue.push(queue.pop())
}
let top = queue.pop()
queue.push(top)
return top
}
func empty() -> Bool {
queue.empty()
}
}
// @lc code=end
题目3:20. 有效的括号
// @lc code=start
class Solution {
var map: [Character: Character] = ["{": "}", "(": ")", "[": "]"]
func isValid(_ s: String) -> Bool {
var chars = [Character]()
for item in Array(s) {
if chars.isEmpty || map[chars.last!] != item {
chars.append(item)
} else {
chars.removeLast()
}
}
return chars.isEmpty
}
}
// @lc code=end
题目4: 1047. 删除字符串中的所有相邻重复项
思路同 20. 有效的括号
// @lc code=start
class Solution {
func removeDuplicates(_ s: String) -> String {
var chars = [Character]()
for char in Array(s) {
if chars.isEmpty || chars.last != char {
chars.append(char)
} else {
chars.removeLast()
}
}
return String(chars)
}
}
// @lc code=end