leetcode [#344]

目录

题目

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

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


解决方案

1
2
3
4
5
6
7
public class Solution {
public String reverseString(String s) {
StringBuilder handler = new StringBuilder(s);
handler.reverse();
return handler.toString();
}
}

注意事项

以下这种写法可以得到正确答案,但是会超时,无法通过。原因是String一旦创建就不可修改,因此遍历中每次为result衔接新增的部分都会创建新对象并将引用指向result,增大了开销。

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
Stack stack = new Stack();
int length = s.length();
for(int i = 0; i < length; i++){
stack.push(s.charAt(i));
}
String result = "";
while(!stack.empty()){
result += stack.pop();
}
return result;
}