Leet Code OJ 344. Reverse String [Difficulty: Easy]

題目:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.

翻譯:
寫一個函數,使用字符串作爲輸入,返回它反轉後的結果。
例如,輸入”hello”,返回”olleh”。

分析:
轉爲字符數組後,將第一個字符和最後一個字符對調,第二個字符和倒數第二個對調,以此類推。

Java版代碼(時間複雜度O(n),空間複雜度O(n)):

public class Solution {
    public String reverseString(String s) {
        char[] chars=s.toCharArray();
        int len=chars.length;
        char temp;
        for(int i=0;i<len/2;i++){
            temp=chars[i];
            chars[i]=chars[len-1-i];
            chars[len-1-i]=temp;
        }
        return new String(chars);
    }
}
發佈了136 篇原創文章 · 獲贊 59 · 訪問量 71萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章