题解 | #翻转单词序列#
翻转单词序列
https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
import java.util.*; public class Solution { public String ReverseSentence(String str) { String[] str2 = str.trim().split(" "); StringBuffer res = new StringBuffer(); for(int i=str2.length-1;i>=0;i--){ if(str2[i].equals(" "))continue; res.append(str2[i]+" "); } return res.toString().trim(); } }
以空格为分割符完成字符串分割后,若两单词间有 x > 1 个空格,则在单词列表 strs 中,此两单词间会多出 x - 1 个 “空单词” (即 "" )。解决方法:倒序遍历单词列表,并将单词逐个添加至 StringBuilder ,遇到空单词时跳过。