[leetcode]reverse string

题目描述

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

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

代码

要求反转一个字符串
使用StringBuilder的reverse函数

1
2
3
public String (String s) {
return new StringBuilder(s).reverse().toString();
}

使用两个指针,分别指向头尾,不断交互

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution{
public String (String s) {
char[] temp = s.toCharArray();
int left = 0;
int right = temp.length - 1;

while(left < right){
char ch = temp[left];
temp[left] = temp[right];
temp[right] = ch;
left++;
right--;
}

return new String(temp);
}
}