翻转字符串(Java实现)


public class E58ReverseString {
    //翻转字符串

    /*问题一:翻转句子但单词内部不翻转*/
    public static String reverseString(String str){
        if (str == null)
            return null;
        char[] chars = str.toCharArray();
        int length = str.length();
        reverse(chars, 0, length - 1);
        int start = 0;
        int end = 0;
        while(start < length){
            if (chars[start] == ' '){
                start++;
                end++;
            }
            if (end == length || chars[end] == ' '){
                reverse(chars, start, end - 1);
                start = end;
            }
            end++;
        }
        return String.valueOf(chars);
    }

    private static void reverse(char[] chars, int start, int end) {
        if (chars.length == 0 || start >= end)
            return;
        while(start < end){
            char temp = chars[start];
            chars[start++] = chars[end];
            chars[end--] = temp;
            //start++;
            //end--;
        }
    }

    /*问题二:左旋转字符串*/
    public static String leftRotateString(String str, int n){
        if (str == null || n > str.length())
            return null;
        int length = str.length();
        char[] chars = str.toCharArray();
        reverse(chars, 0, length - 1);
        reverse(chars, 0, length - n - 1);
        reverse(chars, length - n, length - 1);
        return String.valueOf(chars);
    }

    //测试用例
    public static void main(String[] args){
        String str = "This is a test.";
        System.out.println(E58ReverseString.reverseString(str));
        System.out.println(E58ReverseString.leftRotateString(str, 2));
    }
}

你可能感兴趣的:(剑指offer)