字符串反转 reverse-words-in-a-string @LeetCode

leetcode: https://oj.leetcode.com/problems/reverse-words-in-a-string/

通过率只有14%的题目,虽然很简单,但是要注意几个点:

1. 使用正则的时候,因为我们想要使用\s来代表空格,而\本身是转义符,所以要再加一个\来转义

这是相应的解释:
http://stackoverflow.com/questions/225337/how-do-i-split-a-string-with-any-whitespace-chars-as-delimiters

Something in the lines of

myString.split("\\s+");

this groups all whitespaces as a delimiter... so if i have the string "Hello[space][tab]World", this should yield the strings "Hello" and "World" and omit the empty space between the space and the tab.

As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and sendthat to be parsed. What you want, is the literal "\s", which means, you need to pass "\\s". It can get a bit confusing.

The \\s is equivalent to [ \\t\\n\\x0B\\f\\r]


2. 字符串起始的" "会造成split后有一些空字符串,需要过滤掉
3. append " "的时候,最后一个需要消除。

public class Solution {
    public String reverseWords(String s) {
        if (s == null) {
            return null;
        } else if (s.length() == 0) {
            return "";
        }
        
        // \\ means \
        // + means 1 or more.
        String[] sArray = s.split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = sArray.length - 1; i >= 0; i--) {
            String sElement = sArray[i];
            if (sElement.equals("")) {
                // something like input " is" will genereate some "" empty elements, just ignore them.
                continue;
            }
            sb.append(sArray[i]);
            sb.append(" ");
        }
        // there is the case like input " ", then the output is just "";
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);    
        }
        
        return sb.toString();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值