翻转字符串

方法有:

  1. 翻转字符数组
  2. 字符数组 + StringBuilder
  3. 直接使用 StringBuilder.reverse()
  4. 异或
  5. 递归
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));
        }
    }

}

翻转字符串

上一篇:QT经验(一)——按钮长按事件分析


下一篇:lacp静态和动态区别_LACP基础