1.写一个字符串反转函数.

方法一: (利用递归实现)

public static String reverse1(String s) {
  int length = s.length();
  if (length <= 1)
   return s;
  String left = s.substring(0, length / 2);
  String right = s.substring(length / 2, length);
  return reverse1(right) + reverse1(left);  //调用递归
 }

方法二:(拼接字符串)

public static String reverse2(String s) {
  int length = s.length();
  String reverse = "";
  for (int i = 0; i < length; i++)
   reverse = s.charAt(i) + reverse;
  return reverse;
 }

方法三:(利用数组,倒序输出)

public static String reverse3(String s) {
  char[] array = s.toCharArray();
  String reverse = "";
  for (int i = array.length - 1; i >= 0; i--)
   reverse += array[i];
  return reverse;
 }

方法四:(利用StringBuffer的内置reverse方法)

public static String reverse4(String s) {
  return new StringBuffer(s).reverse().toString();
 }

方法五:(利用栈结构)

public static String reverse7(String s) {
  char[] str = s.toCharArray();
  Stack<Character> stack = new Stack<Character>();
  for (int i = 0; i < str.length; i++)
   stack.push(str[i]);
  
  String reversed = "";
  for (int i = 0; i < str.length; i++)
   reversed += stack.pop();
  
  return reversed;
 }
原文地址:https://www.cnblogs.com/lu97/p/14300731.html