您的位置:首页 > 其它

【LeetCode】Reverse String 解题报告

2016-04-29 21:29 435 查看

Reverse String

[LeetCode]

https://leetcode.com/problems/reverse-string/

Total Accepted: 11014 Total Submissions: 18864 Difficulty: Easy

Question

Write a function that takes a string as input and returns the string reversed.

Example:

Given s = “hello”, return “olleh”.

Ways

方法一

字符串按位翻转:

public class Solution {
public String reverseString(String s) {
StringBuffer answer=new StringBuffer("");
int tail=s.length()-1;
for(int i=tail;i>=0;i--){
answer.append(s.charAt(i));
}
return answer.toString();

}
}


AC:6ms

方法二

转换为字符串后,in-place翻转

public class Solution {
public String reverseString(String s) {
char[] chars=s.toCharArray();
for(int i=0;i<chars.length/2;i++){
char temp=chars[i];
chars[i]=chars[chars.length-1-i];
chars[chars.length-1-i]=temp;
}
return new String(chars);

}
}


AC:3ms

Date

2016/4/29 21:27:57
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode