LeetCode - 反转字符串

题目

请编写一个函数,其功能是将输入的字符串反转过来。

示例:

输入:s = "hello"
返回:"olleh"

解法

很简单的一道题目

https://github.com/biezhihua/LeetCode


@Test
public void test() {
    Assert.assertEquals("olleh", reverseString("hello"));
    Assert.assertEquals("auhihzeib", reverseString("biezhihua"));

}

public String reverseString(String s) {
    return new StringBuffer(s).reverse().toString();
}

@Test
public void test1() {
    Assert.assertEquals("olleh", reverseString1("hello"));
    Assert.assertEquals("auhihzeib", reverseString1("biezhihua"));

}

public String reverseString1(String s) {

    char[] chars = s.toCharArray();
    for (int i = 0; i < chars.length / 2; i++) {
        char tmp = chars[i];
        chars[i] = chars[chars.length - 1 - i];
        chars[chars.length - 1 - i] = tmp;
    }

    return new String(chars);
}
}

猜你喜欢

转载自blog.csdn.net/biezhihua/article/details/79678595