原题描述:https://oj.leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
解题思路:
考虑到字符串中可能包括0个或者多个空格,我使用正则表达式(匹配多个字符串)来对字符串进行分割,然后反向重组字符串即可。
实现代码:
public class Solution {
public String reverseWords(String s) {
String[] strs = s.trim().split("\\s+");//使用正则表达式(匹配0-n个空格)来分割字符串
String result = "";
for(int i=strs.length-1;i>=0;i--){
if(i==0){
result += strs[i].trim();
}else{
result += strs[i].trim() + " ";
}
}
return result;
}
}