LeetCode557 Reverse Words in a String III

来源:互联网 发布:外汇行情软件哪个好 编辑:程序博客网 时间:2024/06/09 20:07

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:Input: "Let's take LeetCode contest"Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

//中间多个空格会保留

解法:

public class Solution {    public String reverseWords(String s) {    String[] strs = s.split(" ");    StringBuilder sb = new   StringBuilder();    for(String str: strs){        StringBuilder temp = new StringBuilder(str);        sb.append(temp.reverse());        sb.append(" ");    }    return sb.toString().trim();    }}
知识点:

StringBuilder/StringBuffer 的reverse方法可以把字符串翻转,注意:String没这个方法



原创粉丝点击