Reverse a given sentence in Java

前端 未结 14 1894
别跟我提以往
别跟我提以往 2020-11-27 04:52

Can anyone tell me how to write a Java program to reverse a given sentence?

For example, if the input is:

\"This is an interview question\"

14条回答
  •  北海茫月
    2020-11-27 05:17

    I don't think you should use any library.. 1) Reverse whole string 2) Reverse each word.

    public static void revWord(char[] a) {
    
        // reverse whole
        revWord(a, 0, a.length);
    
        int st = -1;
        int end = -1;
    
        for (int i = 0; i < a.length; i++) {
    
            if (st == -1 && a[i] != ' ') {
                st = i;
            }
            if (end == -1 && a[i] == ' ' ) {
                end = i;
            }
            if(i == a.length-1){
                end=i+1;
            }
    
            if (st != -1 && end != -1) {
                revWord(a, st, end );
    
                st = -1;
                end = -1;
            }
    
        }
    
    }
    
    public static void revWord(char[] a, int s, int l) {
        int mid = (l - s) / 2;
        l--;
    
        for (int i = 0; i < mid; i++, l--) {
            char t = a[s+i];
            a[s+i] = a[l];
            a[l] = t;
        }
    }
    

    `

提交回复
热议问题