[LeetCode By Go 9]344. Reverse String

题目

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

Example:
Given s = “hello”, return “olleh”.

代码

reverseString.go

package _344_Reverse_String


func ReverseString(s string) string {
    runes := []rune(s)
    for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
        runes[from], runes[to] = runes[to], runes[from]
    }
    return string(runes)
}

测试

reverseString_test.go

package _344_Reverse_String

import "testing"

func TestReverseString(t *testing.T) {
    input := "hello"
    want := "olleh"

    ret := ReverseString(input)

    if ret == want {
        t.Logf("pass")
    } else {
        t.Errorf("fail, want %+v, get %+v", want, ret)
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/3d6bef0975be
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞