Leetcode: Reverse Words in a String

本文详细阐述如何通过使用String的split函数将输入字符串按空格分隔为单词,并实现单词级别的反转。讨论了处理多空格、空字符串以及去除首尾空格的方法,提供了时间与空间复杂度分析。
Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.

这道题很直接的想法就是用String的split函数,把字符串按空格分成一个个子字符串,存到一个String[] strs里面,这时再把strs里的字符串从大到小反转连接,中间加上空格就好了。需要注意如果原来的字符串有multiple spaces, 那会造成我们strs数组里面有一些子字符串是空字符串,我们反转时若遇到这些空字符串,就要把它跳过。时间上split操作是O(N),再一次扫描获得结果,也是O(N)。空间上使用了一个String[] 和StringBuffer,也是O(N)

本题就是需要注意一些语法,比如split函数的参数是String而不能是Char。我写的时候不小心再一次犯了低级错误,String判断是不是空字符串一定不要写成if (str == ""), 要么用equals(), 要么用length()==0来判断

注意 split()函数argument是一个string而不是char

 1 public class Solution {
 2     public String reverseWords(String s) {
 3         if (s==null || s.length()==0) return s;
 4         s.trim();
 5         String[] strs = s.split(" ");
 6         StringBuffer res = new StringBuffer();
 7         for (int i=strs.length-1; i>=0; i--) {
 8             if (strs[i].length() == 0) continue;
 9             res.append(strs[i]);
10             res.append(' ');
11         }
12         return res.toString().trim();
13     }
14 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/4019970.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值