方法有:
- 翻转字符数组
- 字符数组 + StringBuilder
- 直接使用 StringBuilder.reverse()
- 栈
- 异或
- 递归
package com.leetcode2.string;
import java.util.Stack;
public class ReverseString {
//使用字符数组
public String reverseString1(String s) {
char[] c = s.toCharArray();
int l = 0;
int h = s.length() - 1;
while (l < h) {
char t = c[l];
c[l] = c[h];
c[h] = t;
l++;
h--;
}
return new String(c);
}
//使用 StringBuilder
public String reverseString2(String s) {
StringBuilder stringBuilder = new StringBuilder();
char[] c = s.toCharArray();
int h = s.length() - 1;
while (h >= 0) {
stringBuilder.append(c[h]);
h--;
}
return stringBuilder.toString();
}
//直接使用 StringBuilder 中自带方法
public String reverseString3(String s) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(s);
return stringBuilder.reverse().toString();
}
//使用栈
public String reverseString4(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
stack.add(c);
}
StringBuilder stringBuilder = new StringBuilder();
int len = stack.size();
for (int i = 0; i < len; i++) {
stringBuilder.append(stack.pop());
}
return stringBuilder.toString();
}
//使用异或
public String reverseString5(String s) {
char[] c = s.toCharArray();
int l = 0;
int h = s.length() - 1;
while (l < h) {
c[l] ^= c[h];
c[h] ^= c[l];
c[l] ^= c[h];
l++;
h--;
}
return new String(c);
}
//使用递归
public String reverseString6(String s) {
if (s.length() == 1) {
return s;
} else {
//最后一个字符 + 第一个到倒数第二个字符
return s.substring(s.length() - 1) + reverseString6(s.substring(0, s.length() - 1));
}
}
}