[Offer] [58-1] [Flip word order]

Title Description

  Enter an English sentence, reversing the order of words in the sentence, but the order of characters in the word unchanged. For simplicity, punctuation and common letter like treatment. For example, the input string "I am a student.", The output "student. A am I".

Cattle brush off questions address network

Ideas analysis

 First, the entire string flip, and then flipped in a single word

Test Case

  1. Functional test: there are multiple words in a sentence; only one word in a sentence.
  2. Special Test Input: string pointer is a pointer nullptr; content string is empty;
    string only spaces.

Java code

public class Offer058_01 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();
        
    }

     public static String ReverseSentence(String str) {
        return Solution1(str);
    }


    private static String Solution1(String str) {
        if(str==null || str.length() <= 0) {
            return str;
        }
        char[] chars = str.toCharArray();
        
        reverseCore(chars, 0, chars.length-1);
        
        int start = 0;
        int end =0; 
        
        while(start<chars.length){
            while(end<chars.length && chars[end]!=' ')
                end++;
            reverseCore(chars,start,end-1);
            start=++end;
        }
        
        return String.valueOf(chars);
    }
    
    private static void reverseCore(char[] chars ,int start,int end) {
        while(start<end) {
            char tmp = chars[start];
            chars[start]=chars[end];
            chars[end]=tmp;
            start++;
            end--;
        }
    }

    private static void test1() {

    }

    private static void test2() {

    }
    private static void test3() {

    }

}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer581-fan-zhuan-dan-ci-shun-xu.html