简体   繁体   中英

(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. 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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM