当前位置:网站首页>[leetcode sword finger offer 58 - I. flip word order (simple)]

[leetcode sword finger offer 58 - I. flip word order (simple)]

2022-04-23 21:21:00 Minaldo7

subject :

Enter an English sentence , Turn over the order of the words in the sentence , But the order of the characters in the word is the same . For the sake of simplicity , Punctuation is treated like ordinary letters . For example, input string "I am a student. “, The output "student. a am I”.

Example 1:

Input : “the sky is blue”
Output : “blue is sky the”
Example 2:

Input : " hello world! "
Output : “world! hello”
explain : The input string can contain extra spaces before or after , But the reversed characters cannot include .
Example 3:

Input : “a good example”
Output : “example good a”
explain : If there are extra spaces between two words , Reduce the space between inverted words to just one .

explain :

No space characters make up a word .
The input string can contain extra spaces before or after , But the reversed characters cannot include .
If there are extra spaces between two words , Reduce the space between inverted words to just one .

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

class Solution {
    
    public String reverseWords(String s) {
    
        // trim()  Method is used to delete the leading and trailing whitespace of a string ,split() Method splits a string into spaces 
        String[] strings = s.trim().split(" ");
        StringBuilder sb = new StringBuilder();
        for(int i = strings.length-1;i>=0;i--){
    
            //  Prevent consecutive spaces 
            if (strings[i].equals("")) {
    
                continue;
            }
            if(i>0)
                sb.append(strings[i] + " ");
            else
                sb.append(strings[i]);
        }
        return sb.toString();
    }
}

Execution results :

 Insert picture description here

版权声明
本文为[Minaldo7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210544479016.html