【劍指offer-Java版】42翻轉單詞順序VS左旋轉字符串

反轉單詞順序以及左旋轉字符串:輸入一個英文句子,翻轉句子中的單詞順序,單詞內部的字母順序是不變的 – I am a student. -> student. am I

第一步,翻轉句子中的所有字符串,第二步翻轉單詞順序


    public class _Q42<T> {

    public char[] ReverseSentence(String str){
        if(str == null) return null;
        if(str.length() == 0) return str.toCharArray();

        char chars[] = str.toCharArray();
        reverse(chars, 0, str.length() - 1);
        int start = 0; 
        for(int i=0; i<str.length(); i++){
            if(chars[i] == ' '){
                reverse(chars, start, i - 1);
                start = i + 1;
            }
        }
        reverse(chars, start, str.length() - 1);

        return chars;
    }

    private void reverse(char chars[], int begin, int end){
        if(chars == null) return;

        if(begin == end) return;

        char c;
        while(begin < end){
            c = chars[begin];
            chars[begin] = chars[end];
            chars[end] = c;
            begin++;
            end--;
        }
    }

    public char[] LeftRotateString(String str, int n){
        if(str == null) return null;

        char chars[] = str.toCharArray();
        // 先分段旋轉
        reverse(chars, 0 , n - 1);
        reverse(chars, n, str.length() - 1);
        // 最後整體旋轉
        reverse(chars, 0, str.length() - 1);

        return chars;
    }

    }

測試代碼:


    public class _Q42Test extends TestCase {

    _Q42<?> reverse = new _Q42();

    public void test(){
        String str1 = "I am a student.";

        System.out.println(reverse.ReverseSentence(str1)); // 需要對返回結果進行非空判斷

        String str2 = "abcdefg";
        int n = 2;
        System.out.println(reverse.LeftRotateString(str2, n)); // 
    }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章