344. Reverse String
- Total Accepted: 159393
- Total Submissions: 271454
- Difficulty: Easy
- Contributor: LeetCode
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Subscribe to see which companies asked this question.
算法思路
由于测试的数据比较多,一开始想的比较简单,直接利用字符串拼接,没有考虑效率问题,最后结果超时了。
第一种方法是比较简单的方法,直接利用字符串拼接
第二种方法采用末尾和前位交换的方法,但是要注意的是要先把字符串转化为字符数组,因为在交换的过程中不能直接对字符串中的某一字符赋值,
然后返回的时候要new String对象,否则返回的是一个地址
代码一:
public static String reverse(String s){
String result = "";
for(int j=0; j<s.length(); j++){
result = s.charAt(j) + result;
}
return result;
}
代码二:
package easy;
public class ReverseString {
public static String reverseString(String s) {
String string = "";
char[] result = s.toCharArray();
char temp ;
int i = 0;
int j = s.length()-1;
while(i<j){
temp = result[i];
result[i] = result[j];
result[j] = temp;
i++;
j--;
}
return new String(result);
}
public static void main(String[] args){
System.out.println(reverseString("hello"));
}
}