剑指Offer-翻转单词顺序列
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
思路
用栈,单词依次进栈出栈实现翻转
代码实现
package String;
import java.util.Stack;
public class Solution56 {
public static void main(String[] args) {
Solution56 solution56 = new Solution56();
String str = "student. a am I";
System.out.println(solution56.ReverseSentence(str));
}
/**
* 单词依次入栈出栈实现反转
*
* @param str
* @return
*/
public String ReverseSentence(String str) {
if ("".equals(str.trim()) || str.length() == 0 || str == null) {
return str;
}
String[] split = str.trim().split(" ");
Stack<String> stack = new Stack<>();
for (int i = 0; i < split.length; i++) {
stack.push(split[i]);
}
String res = stack.pop();
while (!stack.isEmpty()) {
res += " " + stack.pop();
}
return res;
}
}