[API] 151. Flip the words in the string

Problem Description

Given a string, flip each word in the string one by one.

Example 1:

输入: "the sky is blue"
输出: "blue is sky the"

Example 2:

输入: "  hello world!  "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,
     但是反转后的字符不能包括。

Example 3:

输入: "a good   example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,
     将反转后单词间的空格减少到只含一个。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class Solution {
    public String reverseWords(String s) {
        s = s.trim();//取出开头和结尾两端的空格
        String[] s1 = s.split("\\s+");//按1或者多个空格切割
        //System.out.println(Arrays.toString(s1));
        List<String> sList = Arrays.asList(s1);
        Collections.reverse(sList);

        return String.join(" ", sList);//每个元素按“ ”作为分隔符进行拼接
    }

    public static void main(String[] args) {
        System.out.println(new Solution().reverseWords("  hello  abc   world!  "));
    }
}

A few APIs that are not commonly used are very useful, so record them.

Guess you like

Origin www.cnblogs.com/HoweZhan/p/12672662.html