我是Swift的新手,我花了1小时进行调试,但我仍然不知道它失败的原因。
这是来自leetcode的问题:反转字符串:
输入:“你好”
输出:“olleh”
还有我的代码:
import Foundation
class Solution {
func reverseString(_ s: String) -> String {
// initialize a new null string
var answer = ""
// get the length of the input string
var lengthOfString = s.characters.count
// add the character into the new string
for nums in 0...(lengthOfString-1){
var index = s.index(s.startIndex, offsetBy: lengthOfString)
answer.append(s[index])
lengthOfString-=1
}
return answer
}
}
let a = Solution()
let b = a.reverseString("hello")
print(b)
这是我的错误图片:
答案 0 :(得分:2)
问题出在这个街区:
for nums in 0...(lengthOfString-1){
var index = s.index(s.startIndex, offsetBy: lengthOfString)
answer.append(s[index])
lengthOfString-=1
}
0..<lengthOfString
作为范围。这是一个反转你想要做的字符串的示例:
extension String {
subscript (i: Int) -> Character {
return self[characters.index(startIndex, offsetBy: i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
func reverse() -> String {
let count = characters.count
if count == 0 { return "" }
var result = ""
for i in 0..<count {
result = self[i] + result
}
return result
}
}
let s = "hello"
s.reverse() // print: olleh