Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
public String reverseString(String s) {
char[] ss = s.toCharArray();
int j = ss.length - 1, i = 0;
char temp;
while (i < j) {
temp = ss[i];
ss[i] = ss[j];
ss[j] = temp;
i++;
j--;
}
return String.valueOf(ss);
}
AC了,我想着用栈会不会更加快,没想到。。。
//超时了
public String reverseString(String s) {
Stack<Character> stack = new Stack<Character>();
String str = "";
for (int i = 0; i < s.length(); i++)
stack.add(s.charAt(i));
while(!stack.isEmpty())
str += stack.pop();
return str;
}
这个不能AC