LeetCode 344. Reverse String

problem:

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

Example:
Given s = "hello", return "olleh". 

first:

class Solution {
public String reverseString(String s) {
StringBuilder reversed = new StringBuilder();
char[] array = s.toCharArray();
for(int i=array.length-1;0<=i;i--){
reversed.append(array[i]);
}
return reversed.toString();
}
}

result:

second try:

class Solution {
public String reverseString(String s) {
StringBuffer reversed = new StringBuffer();
char[] array = s.toCharArray();
for(int i=array.length-1;0<=i;i--){
reversed.append(array[i]);
}
return reversed.toString();
}
}

result:

3nd:

class Solution {
public String reverseString(String s) {

char[] array = s.toCharArray();
char[] reversed = new char[array.length];
for(int i=array.length-1;0<=i;i--){
reversed[array.length-1-i]=array[i];
}
return new String(reversed);
}
}

result:

4th:

class Solution {
public String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
}

result:

conclusion:

https://stackoverflow.com/questions/355089/difference-between-stringbuilder-and-stringbuffer

posted @ 2018-04-25 19:40  Zhao_Gang  阅读(59)  评论(0编辑  收藏  举报