import java.util.Stack;
public class ReverseString {
public static void main(String[] args) {
System.out.println(reverse1("abcd"));
System.out.println(reverse2("abcd"));
System.out.println(reverse3("abcd"));
System.out.println(reverse4("abcd"));
System.out.println(reverse5("abcd"));
System.out.println(reverse6("abcd"));
System.out.println(reverse7("abcd"));
}
public final static String reverse1(String str) {
return new StringBuilder(str).reverse().toString();
}
public final static String reverse2(String str) {
String result = "";
int len = str.length();
for (int i = 0; i < len; i++) {
result = str.charAt(i) + result;
}
return result;
}
public final static String reverse3(String str) {
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result = result + str.charAt(i);
}
return result;
}
public final static String reverse4(String str) {
int len = str.length();
Stack<Character> stack = new Stack<Character>();
char[] cs = str.toCharArray();
for (int i = 0; i < len; i++) {
stack.push(str.charAt(i));
}
for (int i = 0; i < len; i++) {
cs[i] = stack.pop();
}
return new String(cs);
}
public final static String reverse5(String str) {
int len = str.length();
if (len == 1) return str;
String left = str.substring(0, len >>> 1);
String right = str.substring(len >>> 1, len);
return reverse5(right) + reverse5(left);
}
public final static String reverse6(String str) {
int len = str.length();
char[] cs = str.toCharArray();
for (int i = 0, j = len - 1; i < len >>> 1; i++, j--) {
cs[i] = str.charAt(j);
cs[j] = str.charAt(i);
}
return new String(cs);
}
public final static String reverse7(String str) {
int len = str.length();
char[] cs = str.toCharArray();
for (int i = 0; i < len >>> 1; i++) {
cs[i] ^= cs[len - 1 - i];
cs[len - 1 - i] ^= cs[i];
cs[i] ^= cs[len - 1 - i];
}
return new String(cs);
}
}
打开App,阅读手记