leetcode151-翻转字符串里的单词

原题

给定一个字符串,逐个翻转字符串中的每个单词。

示例 1:

输入: “the sky is blue”
输出: “blue is sky the”

示例 2:

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

示例 3:

输入: “a good example”
输出: “example good a”
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

解法

思想

直接使用jdk中String的trim()split()方法得到单词的数组,或者遍历字符串字符,记录单词数组。再反向遍历输出。

代码

class Solution {
    public String reverseWords(String s) {
        //"\\s+"代表正则表达式1个或多个空白字符
        String[] words = s.trim().split("\\s+");
        int size = words.length;
        StringBuilder str = new StringBuilder();
        for(int i = 0;i<size;i++){
            str.append(words[size-1-i]);
            if(i!=size-1) str.append(" ");
        }
        return str.toString();
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode151-%e7%bf%bb%e8%bd%ac%e5%ad%97%e7%ac%a6%e4%b8%b2%e9%87%8c%e7%9a%84%e5%8d%95%e8%af%8d/

发表回复

登录后才能评论