[leetCode]剑指 剑指 Offer 58 - I. 翻转单词顺序、 II. 左旋转字符串

解法 双指针

使用两个指针定位每个单词,然后加入StringBuffer,最后转为字符串。

class Solution {
    public String reverseWords(String s) {
        if (s == null) return "";
        s = s.trim();
        if(s.length() == 0) return "";
        StringBuffer buffer = new StringBuffer();
        int begin = s.length() - 1 , end = begin;
        while (begin >= 0) {
            while(begin >=0 && s.charAt(begin) != ' ') --begin;
            buffer.append(s.substring(begin+1, end+1) + " ");
            while(begin >=0 && s.charAt(begin) == ' ') --begin;
            end = begin;
        }
        returan buffer.toString().trim();
    }
}

解法一

直接利用javaAPI即可完成左旋

class Solution {
    public String reverseLeftWords(String s, int n) {
        if (s == null || n >= s.length()) return s;
        StringBuffer sb = new StringBuffer();
        sb.append(s.substring(n, s.length()));
        sb.append(s.substring(0, n));
        return sb.toString();
    }
}

翻转

将字符串分为两部分:[0,n)、[n,length)。将这两部分各自 翻转然后将整个字符串翻转即可完成左旋

class Solution {
    public String reverseLeftWords(String s, int n) {
        if (s == null || n >= s.length()) return s;
        char[] chars = s.toCharArray();
        reverse(chars, 0, n-1);
        reverse(chars, n, chars.length - 1);
        reverse(chars, 0, chars.length - 1);
        return new String(chars);
    }

    private void reverse(char[] chars, int begin, int end) {
        while (begin < end) {
            char temp = chars[begin];
            chars[begin] = chars[end];
            chars[end] = temp;
            begin++;
            end--;
        }
    }
}
posted @ 2020-09-22 10:15  消灭猕猴桃  阅读(63)  评论(0编辑  收藏  举报