输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"
解题思路
将字符串以空格分割成字符串数组
倒序遍历数组, 拼接每个单词
代码
class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split(" ");
StringBuilder result = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
if ("".equals(words[i])) {
continue;
}
result.append(words[i]).append(" ");
}
return result.toString().trim();
}
}