【字符串反转总结】Java中七种方法实现

算法比较简单,注释就能说明问题,直接上代码!

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

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 reverse5(String orig) {
  char[] s = orig.toCharArray();
  int n = s.length - 1;
  int halfLength = n / 2;
  for (int i = 0; i <= halfLength; i++) {
   char temp = s[i];
   s[i] = s[n - i];
   s[n - i] = temp;
  }
  return new String(s);
 }

方法六:(利用位异或操作,交换两头数据)具体交换原理,参考上一篇文章

public static String reverse6(String s) {
  
  char[] str = s.toCharArray();
  
  int begin = 0;
  int end = s.length() - 1;
  while (begin < end) {
   str[begin] = (char) (str[begin] ^ str[end]);
   str[end] = (char) (str[begin] ^ str[end]);
   str[begin] = (char) (str[end] ^ str[begin]);
   begin++;
   end--;
  }
  return new String(str);
 }


方法七:(利用栈结构)

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;
 }
有其它方法,欢迎交流!兰州理工大学

阅读更多
个人分类: 字符串反转 算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭