Swift算法2-Reverse a String
2016-07-07 本文已影响0人
四毛哥掉落的鳞片
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
ok this is the solution i got:
class Solution {
func reverseString(s: String) -> String {
var stringArray = [s]
let reversedStr = stringArray.map() { String($0.characters.reverse()) }
return reversedStr[0]
}
}
and this is the version i made before, and it cannot be compiled at leetcode. whyyyyyyyyyyy??????
well i know this code is ugly but it is the first solution i got for the reversing.....
class Solution {
func reverseString(s: String) -> String {
var stringArray = [Character]()
var newS = ""
if (s == "") {return s}
for c: Character in s.characters {
stringArray += [c]
}
var l = stringArray.count - 1
for (l; l >= 0; l--) {
/*
for i in 0..<l/2 {
var j: Character
j = stringArray[l-i]
stringArray[l-i] = stringArray[i]
stringArray[i] = j
}
*/
let e = stringArray.removeAtIndex(l)
newS.append(e)
}
return newS
}
}```