题解 | #单词倒排#
单词倒排
http://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
import java.util.*;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String s = sc.nextLine();
//去除语句左右两端空格
int left = 0, right = s.length() - 1;
while(left <= right && s.charAt(left) == ' ') left++;
while(left <= right && s.charAt(right) == ' ') right--;
//双端队列
Deque<String> queue = new ArrayDeque<>();
StringBuilder sb = new StringBuilder();
while(left <= right){
char c = s.charAt(left);
//当sb不为空且当前字符不为字母,双端队列头部加入sb,并设sb为空
if(sb.length() != 0 && (!Character.isLetter(c))){
queue.offerFirst(sb.toString());
sb.setLength(0);
}else if(Character.isLetter(c)){ //当前字符为字母时加入sb
sb.append(c);
}
left++;
}
//这里是加上最后一个单词,因为按照循环设定的第一个条件最后一个单词是没加上的
queue.offerFirst(sb.toString());
//利用join分隔元素输出
System.out.println(String.join(" ", queue));
}
}
}