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);
}
}
發佈了251 篇原創文章 · 獲贊 240 · 訪問量 71萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章