美文网首页LeetCode
344. Reverse String

344. Reverse String

作者: 小万叔叔 | 来源:发表于2017-01-13 09:54 被阅读4次
/**
 Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

Subscribe to see which companies asked this question
*/

/*
 Thinking:
 这个比较简单,只需要一左一右交换,知道相遇就可以了
 */

func reverseString(_ s: String) -> String {
    guard s.lengthOfBytes(using: .ascii) > 1 else {
        return s
    }
    
    var array = s.characters.map { String($0) }
    
    func swapArray(_ left: Int, _ right: Int) {
        if (left != right) {
            swap(&array[left], &array[right])
        }
    }
    
    var left = 0
    var right = array.count - 1
    while left < right {
        swapArray(left, right)
        left += 1
        right -= 1
    }
    
    return array.joined()
}

reverseString("a")
reverseString("ab")
reverseString("acddeasfaf")

相关文章

  • 2019-04-08

    LeetCode 344. Reverse String Description Write a function...

  • 344. Reverse String

    344. Reverse String Easy Write a function that reverses a...

  • 344. 反转字符串

    344. 反转字符串[https://leetcode.cn/problems/reverse-string/] ...

  • 344. Reverse String

    344. Reverse String Python: 最Pythonic的解法咯 Discuss有人问如下解法为...

  • String

    唐博主刷了String,我那周太忙了,需要慢慢自己补啦。344. Reverse String : Easy3....

  • 344. Reverse String

    https://leetcode.com/problems/reverse-string/description/...

  • 344. Reverse String

    Leetcode Day 1 344 Reverse String 题目:Write a function tha...

  • 344. Reverse String

    Problem Write a function that takes a string as input and...

  • 344. Reverse String

    Write a function that takes a string as input and returns...

  • 344. Reverse String

    1.描述 Write a function that takes a string as input and re...

网友评论

    本文标题:344. Reverse String

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