(java)需要使用堆栈反转字符串语句

brqmpdu1  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(341)

给出一个完整的句子,是否有可能在不反转单词本身的情况下反转堆栈。i、 玛丽有一只小羊羔。它的羊毛像雪一样白。新句子-小羊有玛丽。雪如白雪被它的羊毛所覆盖。基本上卡在环部分。出于某种原因,我让它显示单词和句号,但就我的一生而言,我似乎无法让push/pop参数做我想让他们做的事情。我把所有的意见,因为它可以帮助我得到我的思想秩序,当我休息时,从编码像我会做的,现在我打破我的头在我的电脑上。

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

62o28rlo1#

可以使用 Stack 自Java1.0以来就存在的实现(尽管即使提到的javadoc页面也建议使用 Deque 接口及其实现(提供更丰富的后进先出操作集):

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.

相关问题