[英](Java) Need to reverse a string sentence using stack
Given a full sentence, is it possible to reverse the stack without reverse the words themselves.给定一个完整的句子,是否可以在不反转单词本身的情况下反转堆栈。 ie initial sentence - Mary had a little lamb.
即最初的句子 - 玛丽有一只小羊羔。 Its fleece was white as snow.
它的羊毛洁白如雪。 new sentence - Lamb little a had mary.
新句子——小羊羔有玛丽。 Snow as white was fleece its.
雪白如羊毛。 Basically stuck on the loop portion.
基本上卡在循环部分。 For some reason I get it to display the words and break at the period, but for the life of me, I cant seem to get the push/pop args to do what I would like for them to do.
出于某种原因,我让它显示单词并在期间中断,但对于我的生活,我似乎无法让 push/pop args 做我希望他们做的事情。 I put all the comments because it helps me get my thoughts in order when I take a break from coding like I will be doing right now before I break my head over my computer.
我把所有的评论都写下来了,因为当我从编码中休息一下时,它可以帮助我整理我的想法,就像我现在正在做的那样,然后在我的电脑上打断我的头。
public class ReverseTheStack
{
private static LinkedList<Object> list = new LinkedList<Object>();
public static class Stack
{
public void push(Object obj)
{
list .addFirst(obj);
}
public Object pop()
{
return list.removeFirst();
}
}
public static void main(String [] args)
{
//First hard code the sentence for testing
String sentence = "Mary had a little lamb. Its fleece was white as snow.";
//The scanner is created with the String obj inside it
Scanner in = new Scanner(sentence);
//Set the scanner's delimiter to a period and the space after: "\\. "
in.useDelimiter(" ");
//Create a stack
Stack sentenceReversal = new Stack();
while(in.hasNext())
{
sentenceReversal.push(in.next());
if(in.toString().contains("\\."))
{
System.out.println(sentenceReversal.pop());
}
}
//Close the scanner
in.close();
}
}
It's possible to use Stack
implementation existing since Java 1.0 (though even the mentioned Javadoc page recommends to use Deque
interface and its implementaitons offering richer set of LIFO operations):可以使用自 Java 1.0 以来存在的
Stack
实现(尽管即使提到的 Javadoc 页面也建议使用Deque
接口及其实现提供更丰富的 LIFO 操作集):
String str = "Mary had a little lamb. Its fleece was white as snow.";
Stack<String> stack = new Stack<>();
StringBuilder sb = new StringBuilder(); // build result string
// splitting text into sentences
for (String sentence : str.split("\\.\\s*")) {
stack.clear();
// splitting into words
for (String word : sentence.split("\\s+")) {
stack.push(word.toLowerCase()); // fix letter case
}
boolean first = true;
while (!stack.empty()) {
String word = stack.pop();
if (first) {
// capitalize the first letter in the reversed sentence
first = false;
word = word.substring(0, 1).toUpperCase() + word.substring(1);
}
if (sb.length() > 0) {
sb.append(' ');
}
sb.append(word);
}
sb.append('.');
}
System.out.println(sb);
Output:输出:
Lamb little a had mary. Snow as white was fleece its.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.