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

来源:互联网 发布:一台电脑装两个数据库 编辑:程序博客网 时间:2024/06/05 16:59

题目:
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);    }}
0 0