您的位置:首页 > 其它

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

2016-06-23 13:50 435 查看
题目:

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: