比如字符串“dog loves pig”,翻转成“pig loves dog”

“how are you”翻转成“you are how”

思路是把字符串整体逆序,然后找到每个单词,再把每个单词的字符逆序一遍

可是现在的面试要求就是不能用String,不能用库函数

给定你的就是字符数组char[] c = new char[] {'h', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u'};

当然要求不能用String s = new String(c);不能操作字符串。

以下思路参考左程云的书:

 

import java.util.Scanner;

public class Main {
    public static void rotateWord(char[] chas) {
        if (chas == null || chas.length == 0) {
            return;
        }
        reverse(chas, 0, chas.length - 1);
        int l = -1;
        int r = -1;
        int len = chas.length;
        for (int i = 0; i < len; ++i) {
            // 这个字符不为空格,如果前一个为空,则记录l,如果后一个为空,则记录r
            // 若为起始点或者最后,直接记录,主要考虑只有一个单词情况
            if (chas[i] != ' ') {
                l = i == 0 || chas[i - 1] == ' ' ? i : l;
                r = i == len - 1 || chas[i + 1] == ' ' ? i : r;
            }
            if (l != -1 && r != -1) {
                reverse(chas, l, r);
                l = -1;
                r = -1;
            }
        }
    }

    private static void reverse(char[] chas, int start, int end) {
        char temp = 0;
        while (start < end) {
            temp = chas[start];
            chas[start] = chas[end];
            chas[end] = temp;
            ++start;
            --end;
        }
    }

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        String s = cin.nextLine();
        cin.close();
        char[] c = s.toCharArray();
        // ===================================
        rotateWord(c); // 这里为需要编写的代码
        // ===================================
        for (char cc : c) {
            System.out.print(cc);
        }
        System.out.println();
    }
}

=========================Talk is cheap, show me the code=======================