雙指針法
func reverseString(_ s: inout [Character]) {
if s.count == 0 {
return
}
var x = 0
var y = s.count - 1
while(x < y){
s.swapAt(x, y)
x += 1
y -= 1
}
}
遞歸
func reverseString_methods2(_ s: inout [Character]) {
if s.count == 0 {
return
}
recursive_reverseString(&s, 0, s.count-1)
}
func recursive_reverseString(_ s: inout [Character], _ start:Int, _ end : Int) {
if start >= end {
return
} else {
s.swapAt(start, end)
recursive_reverseString(&s,start+1,end-1)
}
}
自帶函數(shù)
func reverseString_methods3(_ s: inout [Character]) {
if s.count == 0 {
return
}
s = s.reversed()
}