LeetCode 1 Reverse Words in a String

来源:互联网 发布:阿里旺旺网络连接失败 编辑:程序博客网 时间:2024/05/21 00:45

Given an input string, reverse the string word by word.

For example:

Given s = "the sky is blue",

return "blue is sky the".

原题链接

这道题没有什么技巧,主要是考察对字符串操作的掌握。

注意点:

1,对一个空字符串使用split(“ ”)会返回一个长度为1的空格字符串;

2,split(" ")对每一个空格都起作用,所以如果想把相连的空格当做一个处理,应该用split(" +"),即一个或多个空格;

3,用StringBuilder代替String来避免不必要空间的开辟。

public class Solution {    public String reverseWords(String s) {        if(s==null)             return null;        String newStr = s.trim();        if(newStr.length()==0)             return newStr;        String[] words = newStr.split(" +");        StringBuilder sb = new StringBuilder();        for(int i=words.length-1; i>=0; i--){            sb.append(words[i]);            if(i!=0){                sb.append(" ");            }        }        return sb.toString();    }}


0 0
原创粉丝点击