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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章