Sword refers to Offer-41-flip the word

Title description

Niuke recently came to Fish, a new employee. 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 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 these words one by one. Can you help him?

Idea analysis

This is completely inverted. Mainly pay attention to the handling of spaces inside. (It is also done with a sliding window, but I think it’s too much trouble and solve it directly with violence)

Code

public class Solution {
    
    
    public String ReverseSentence(String str) {
    
    
        //这里对于str的判断,需要注意。
        if(str.trim().equals("")){
    
    
            return str;
        }
        String[] temp = str.split(" ");
        StringBuffer sb = new StringBuffer();
        for(int i = temp.length - 1 ; i >= 0 ;i--){
    
    
            sb.append(temp[i]).append(" ");
        }
        //尾部空格需要删除
       sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107453102