557. 反转字符串中的单词 III(难度:简单)

一、题目描述

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例:
输入:“Let’s take LeetCode contest”
输出:“s’teL ekat edoCteeL tsetnoc”
提示:
在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

二、题目答案

class Solution {
    public String reverseWords(String s) {
        String words[] = s.split(" ");
        StringBuilder str = new StringBuilder();
        for(String word : words)
            str.append(new StringBuilder(word).reverse().toString() + " ");
        return str.toString().strip();

    }
}

三、题目解析

1.split()

public String[] split​(String regex)

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string “boo:and:foo”, for example, yields the following results with these expressions:

RegexResult
:{ “boo”, “and”, “foo” }
o{ “b”, “”, “:and:f” }

Parameters:
regex - the delimiting regular expression
Returns:
the array of strings computed by splitting this string around matches of the given regular expression
Throws:
PatternSyntaxException - if the regular expression’s syntax is invalid
Since:
1.4
See Also:
Pattern

  我们这儿使用split来分隔空号,然后将分隔后的字符串一次存入words[]。

2.StringBuilder() or StringBuffer()
  StringBuilder类在Java5中引入。这个类的前身是StringBuffer,它的效率稍微低些,但是允许采用多线程的方式添加和删除字符。如果所有字符串编辑操作都是在单线程中执行的,则应该使用StringBuilder。

3.toString()
  toString()返回一个与构建器StringBuilder或缓冲器StringBuffer内容相同的字符串。

4.strip()
  返回一个新的字符串。这个字符串将删除原始字符串头部尾部的空格。
  当然也可以采用trim(),此时将会删除原始字符串头部尾部小于等于U+0020的字符。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值