117 翻转字符串(1)- 单词翻转
Table of Contents

ac

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static Scanner sc = new Scanner(System.in);

    public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws Exception {
        String s = reader.readLine();
        int len = s.length();
        char[] chars = s.toCharArray();

        // 翻转整个字符串
        revers(chars, 0 , len-1);

        // 翻转单词
        int l = -1;
        int cnt = 0;
        for(int i=0;i<len;i++){
            if(chars[i] == ' '){
                if(cnt != 0){
                    revers(chars, l, l+cnt-1);
                }
                cnt = 0;
            }else {
                if(cnt == 0){
                    l = i;
                    cnt = 1;
                }else {
                    cnt++;
                }
            }
        }
        if(cnt != 0){
            revers(chars, l, l+cnt-1);
        }

        // 再一次整体翻转
        revers(chars, 0 , len-1);

        // print
        System.out.println(chars);
    }

    static void revers(char[] chars, int l, int r) {
        char temp;
        while(l < r) {
            temp = chars[l];
            chars[l] = chars[r];
            chars[r] = temp;
            l++;
            r--;
        }
    }

}
/*
i am a student

i ma a tneduts

// 1.
tneduts a ma i
// 2.
student a am i
// 3.
i ma a tneduts
*/