美文网首页
Swift算法2-Reverse a String

Swift算法2-Reverse a String

作者: 四毛哥掉落的鳞片 | 来源:发表于2016-07-07 15:12 被阅读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
        }
    }```

    相关文章

      网友评论

          本文标题:Swift算法2-Reverse a String

          本文链接:https://www.haomeiwen.com/subject/jmlljttx.html