字符串反转 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();
    }
}

你可能感兴趣的:(字符串反转 reverse-words-in-a-string @LeetCode)