【问题标题】:(Java) Need to reverse a string sentence using stack(Java) 需要使用栈反转一个字符串语句
【发布时间】:2021-03-03 09:45:06
【问题描述】:

给定一个完整的句子,是否可以在不反转单词本身的情况下反转堆栈。 IE。 第一句话——玛丽有一只小羊羔。它的羊毛像雪一样白。 新句子——Lamb little a had mary。雪白如绒。 基本上卡在循环部分。出于某种原因,我让它显示单词并在期间中断,但是对于我的生活,我似乎无法让 push/pop args 做我想让他们做的事情。我把所有的 cmets 都放在了,因为它可以帮助我在编码休息时理清思路,就像我现在在我的电脑前摔倒之前所做的那样。

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();
    }
}

【问题讨论】:

  • 你不想把所有东西都推上去,然后在最后全部弹出吗?那不是你的代码所做的......为什么list static ?

标签: java stack


【解决方案1】:

可以使用自 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);

输出:

Lamb little a had mary. Snow as white was fleece its.

【讨论】:

  • 我强烈建议使用Deque 及其实现ArrayDeque,只要StackVector 被认为已过时。
  • @NikolasCharalambidis,这个问题听起来好像类名 Stackpush/pop 方法很重要:)
猜你喜欢
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-12
相关资源
最近更新 更多