Java字符串反转

/*递归1*/
String reverse1(String s)
{
    int len = s.length();
    if(len <= 1 || s == null)//注意递归结束条件
        return s;
    String left = s.substring(0, length / 2);
    String right = s.substring(length / 2, length);
    return reverse1(right) + reverse2(left);
}

/*递归2*/
String reverse2(String s)
{   
    if(s.length() <= 1 || s == null)//注意递归结束条件
        return s;
    return reverseString(s.substring(1)) + s.charAt(0);
} 

/*倒序相加1*/
String reverse3(String s)
{
    int len = s.length();
    String res = "";
    for(int i = 0; i < len; i++)
        res = s.charAt(i) + res;
    return res; 
} 

/*倒序相加2*/
String reverse4(String s)
{
    char[] array = s.toCharArray();
    String res = "";
    for(int i = len - 1; i >= 0; i--)
        res = res + array[i];
    return res;
} 

/*异或交换(无重复字符时)*/
String reverse5(String s)
{
    char[] array = s.toCharArray();
    int halfLen = (s.length() - 1) / 2;
    for(int i = 0; i <= halfLen; i++)
    {
        s[i]     = (char)(s[i] ^ s[n - i]);
        s[n - i] = (char)(s[i] ^ s[n - i]);
        s[i]     = (char)(s[i] ^ s[n - i]);
    }
    return new String(array);
} 

/*辅助变量交换*/
String reverse6(String s)
{
    char[] array = s.toCharArray();
    int lo = 0;
    int hi = s.length() - 1;
    while(lo < hi)
    {
        char temp;
        temp = s[lo];
        s[lo] = s[hi];
        s[hi] = temp;
        lo++; hi--;
    }
    return new String(array);
} 

/*调用reverse方法*/
String reverse7(String s)
{
    return new StringBuffer(s).reverse().toString();
} 

/*使用stack*/
String reverse8(String s)
{
    char[] array = s.toCharString();
    Stack<Character> stack = new Stack<>();
    for(int i = 0; i < s.length(); i++)
        stack.push(s[i]);
    String res = "";
    for(int j = 0; j < s.length(); j++)
        res = res + stack.pop();
    return res;
}

你可能感兴趣的:(Java字符串反转)