How to combine two lines using the Stack push and pop operations?

If I have two lines, say str1 & str2

 str1 = I to cricket chess str2 = like play and 

I want the result to be as follows:

"I like to play cricket and chess."

This can be done using push and pop stack operations. The algorithm must be independent of the programming language. The strings mentioned above can be of any length.

+4
source share
2 answers

It is very simple. You just need to push first word from the first line onto the stack, then push first word from the second line, then do the same for the second words, then to three words, etc.

After that, you need pop remove each element from the stack and push to the second stack to invert the sequence. Then you just pop each item from the second stack and add it to the resulting string.

+2
source

From what you have given, you have to make some assumptions.

Assumptions:

  • Words in a sentence alternate between both lines
  • One line will contain no more than one word than another line
  • Space is a word delimiter.

The algorithm would be like this:

  • For each row:
  • divide the string up into an array, by a space character
  • Find the array with the longest length
  • Starting with the array with the longest length (call this array B and another array O)
  • At the end of the array
  • push the arrayB element onto the stack,
  • push the arrayO element onto the stack,
  • Repeat until all elements in each array are pressed alternating between two arrays.
  • When done, put the stack in an array,
  • Attach the array to the string using space as a separator.
+1
source

Source: https://habr.com/ru/post/1441197/


All Articles