输入  abc efg.

输出  efg. abc

public String reserve(String str) {
        if (null == str || str.length() == 0) {
            return str;
        }
        char[] chars = str.toCharArray();
        int length = chars.length - 1;
        //先翻转整体
        reserve(chars, 0, length);
        int blankPos = 0;
        for (int i = 0; i <= length; i++) {
            //再翻转部分
            if (chars[i] == ' ') {
                reserve(chars, blankPos, i - 1);
                blankPos = i + 1;
            } else if (i == length) {
                reserve(chars, blankPos, i);
            }
        }
        return new String(chars);
    }
    
    public char[] reserve(char[] chars, int left, int right) {
        if (null == chars || chars.length <= 0 || left < 0 || left >= right) {
            return chars;
        }
        for (int i = left; i < right; i++) {
            char temp = chars[i];
            chars[i] = chars[right];
            chars[right] = temp;
            right--;
        }
        return chars;
    }

 

posted on 2019-03-28 17:09  反光的小鱼儿  阅读(227)  评论(0编辑  收藏  举报