您的位置:首页 > 其它

【Leetcode】之 Reverse Words in a String

2016-03-21 13:56 344 查看

一.问题描述

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

For example,

Given s = “the sky is blue”,

return “blue is sky the”.

二.我的解题思路

java的String类提供了较为丰富的方法,因此直接使用java的方法就可以较好的解决这个问题,如下:

public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}

String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = arr.length - 1; i >= 0; --i) {
if (!arr[i].equals("")) {
sb.append(arr[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: