题解 | #反转单词顺序#
翻转单词序列
http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
一般遇到反转的问题要优先考虑栈,利用先进后出的性质。本题可以先用split方法将strng拆成子字符串,然后压入栈,再弹出。要注意删掉最后的空格。
import java.util.*;
public class Solution {
public String ReverseSentence(String str) {
Stack<String> stack = new Stack<>();
String[] sub = str.split(" ");
for(String sub1:sub){
stack.push(sub1);
}
String cur = new String();
while(stack.size()>0){
cur = cur + stack.pop()+" ";
}
cur = cur.substring(0,cur.length()-1);
return cur;
}
}