【LeetCode】字符串反转函数的几个算法 Reverse String

题目:

Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.

//反转字符串 方法1.最容易想到
public String reverseString(String s) {
    if(s == null)
        return null;
    int len = s.length();
    char[] cTmp = s.toCharArray();
    char[] cRes = new char[len];
    for (int i = 0; i < len; i++) {
        cRes[i] = cTmp[len-1-i];
    }
    String sRes = String.valueOf(cRes);
    return sRes;
}
方法2.省了个过渡的数组
public String reverseString1(String s) {
    if(s == null)
        return null;
    int len = s.length();
    char[] cTmp = s.toCharArray();
    char c;
    for (int i = 0; i < len>>1; i++) {
        c = cTmp[i];
        cTmp[i] = cTmp[len -1 - i];
        cTmp[len -1 - i] = c;
    }
    String sRes = String.valueOf(cTmp);
    return sRes;
}

方法3. 方法2的另一种表现形式
public String reverseString2(String s){
        if(s == null || s.length() == 0)
            return "";
        char[] cs = s.toCharArray();
        int begin = 0, end = s.length() - 1;
        while(begin <= end){
            char c = cs[begin];
            cs[begin] = cs[end];
            cs[end] = c;
            begin++;
            end--;
        }
        return new String(cs);
}
方法4.使用现成的函数
public String reverseString3(String s){
    StringBuilder sb = new StringBuilder(s);
    return sb.reverse().toString();//reverse源码中也是用reverseString1()这种方法,法234基本相同。StringBuilder线程不安全

}

    原文作者:SprinLa
    原文地址: https://blog.csdn.net/youyaecho/article/details/51442697
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞