您的位置:首页 > 其它

Leetcode Reverse Words in a String

2015-10-11 02:35 453 查看
Given an input string, reverse the string word by word.

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

解题思路:

用trim() 和splite("\\s+")把String 切割成一个一个word, 然后用StringBuilder 重建String. O(n) time and O(n) Space

Java code:

public String reverseWords(String s) {
if( s == null || s.length() == 0 ){
return "";
}
String[] splited = s.trim().split("\\s+");
int len = splited.length;
StringBuilder sb = new StringBuilder();
for(int i = len-1; i >= 0; i--){
sb.append(splited[i] + " ");
}
return sb.toString().trim();
}


Reference:

1. https://leetcode.com/discuss/56712/straightforward-java-solution-using-split
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: