您的位置:首页 > 编程语言 > Java开发

LeetCode | Reverse Words in a String

2014-05-04 22:00 441 查看
原题描述: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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息