×

# 数组

``````// 声明一个不可修改的数组
let nums = [1, 2, 3]
let nums = [Int](repeating: 0, count: 5)

// 声明一个可以修改的数组
var nums = [3, 1, 2]
// 增加一个元素
nums.append(4)
// 对原数组进行升序排序
nums.sort()
// 对原数组进行降序排序
nums.sort(by: >)
// 将原数组除了最后一个以外的所有元素赋值给另一个数组
let anotherNums = Array(nums[0 ..< nums.count - 1])
``````

``````// 用数组实现栈
class Stack {
var stack: [AnyObject]

init() {
stack = [AnyObject]()
}

func push(object: AnyObject) {
stack.append(object)
}

func pop() -> AnyObject? {
if (!isEmpty()) {
return stack.removeLast()
} else {
return nil
}
}

func isEmpty() -> Bool {
return stack.isEmpty
}

func peek() -> AnyObject? {
return stack.last
}
}
``````

# 集合和字典

``````func twoSum(nums: [Int], _ target: Int) -> Bool {
var set = Set<Int>()

for num in nums {
if set.contains(target - num) {
return true
}

set.insert(num)
}

return false
}
``````

``````func twoSum(nums: [Int], _ target: Int) -> [Int] {
var dict = [Int: Int]()

for (i, num) in nums.enumerated() {
if let lastIndex = dict[target - num] {
return [lastIndex, i]
} else {
dict[num] = i
}
}

fatalError("No valid output!")
}
``````

# 字符串

``````// 字符串和数字之间的转换
let str = "3"
let num = Int(str)
let number = 3
let string = String(num)

// 字符串长度
let len = str.characters.count

// 访问字符串中的单个字符，时间复杂度为O(1)
let char = str[str.characters.index(str.characters.startIndex, offset: n)]

// 修改字符串
str.removeAtIndex(n)
str.append("c")
str += "hello world"

// 检测字符串是否是由数字构成
func isStrNum(str: String) -> Bool {
return Int(str) != nil
}

// 将字符串按字母排序(不考虑大小写)
func sortStr(str: String) -> String {
var chars = [Character](str.characters)
chars.sort()
return String(chars)
}
``````

Given an input string, reverse the string word by word.
A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?

• 每个单词长度不一样
• 空格需要特殊处理

``````fileprivate func swap<T>(_ chars: inout [T], _ p: Int, _ q: Int) {
(chars[p], chars[q]) = (chars[q], chars[p])
}
``````

• 整个字符串翻转，"the sky is blue" -> "eulb si yks eht"
• 每个单词作为一个字符串单独翻转，"eulb si yks eht" -> "blue is sky the"

``````func reverseWords(s: String?) -> String? {
guard let s = s else {
return nil
}

var chars = Array(s.characters), start = 0
_reverse(&chars, 0, chars.count - 1)

for i in 0 ..< chars.count {
if i == chars.count - 1 || chars[i + 1] == " " {
_reverse(&chars, start, i)
start = i + 2
}
}

return String(chars)
}

fileprivate func _reverse<T>(_ chars: inout [T], _ start: Int, _ end: Int) {
var start = start, end = end

while start < end {
_swap(&chars, start, end)
start += 1
end -= 1
}
}
``````

# 总结

Swift中数组、字符串、集合以及字典是最基本的数据结构，但是围绕这些数据结构的问题层出不穷。幸运的是解决方法也并不是千变万化、高深莫测，大家做好相应的积累即可。下期我们讲链表。