[String] Reverse the word order column

Title description

Niuke recently came to Fish, a new employee, and he always took an English magazine every morning and wrote some sentences in his notebook. My colleague Cat was very interested in what Fish wrote. One day he borrowed it from Fish to read it, but he couldn't read it. For example, "student. a am I". Later I realized that this guy had reversed the order of the words in the sentence. The correct sentence should be "I am a student." Cat is not good at flipping the order of these words one by one. Can you help him?

Example 1
Input
"nowcoder. a am I" and
return value
"I am a nowcoder."


This question is not difficult. Split the string with spaces to get the words, and then combine them in reverse order to get the reversed word sequence. It is necessary to pay attention to the situation where it is all spaces, empty strings, and only one word . The following code is the first time I submitted it. I didn't know these conditions when I wrote it. After reading the solution, I found that these special situations exist, but the code happens to be Can handle the corresponding situation.

import java.util.ArrayList;

public class Solution {
    
    
    public String ReverseSentence(String str) {
    
    
        ArrayList<String> list = new ArrayList<>();
        int start = 0;
        for (int i = 0; i < str.length(); i++) {
    
    
            if (str.charAt(i) == ' ') {
    
    
                list.add(str.substring(start, i));
                start = i + 1;
            }
        }
        list.add(str.substring(start));
        String res = "";
        for (int i = list.size() - 1; i > 0; i--)
            res += list.get(i) + " ";
        res += list.get(0);
        return res;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43486780/article/details/113810736