【LeetCode】#151翻转字符串里的单词(Reverse Words in a String)
题目描述
给定一个字符串,逐个翻转字符串中的每个单词。
示例
输入: “the sky is blue”,
输出: “blue is sky the”.
Description
Given an input string, reverse the string word by word.
Example
Input: “the sky is blue”,
Output: “blue is sky the”.
解法
public class Solution {
public String reverseWords(String s) {
String[] group = s.split(" ");
StringBuilder sb = new StringBuilder(group.length);
for (int i = group.length - 1; i >= 0; i--) {
if (!group[i].equals("") && !group[i].equals(" "))
sb.append(group[i]).append(" ");
}
return sb.toString().trim();
}
}