Description: This topic specifies the order of inbound and outbound stacks and prints the order of inbound and outbound stacks.
Example: If the number of incoming and outgoing Stacks is 123, push1 | push2 | pop2 | pop1 | push3 | pop3 is printed.
The Code is as follows: (the code written at the time was not optimized)
[Java]
Import java. util. collections;
Import java. util. Stack;
Import java. util. StringTokenizer;
Public class Solution2
{
Private String calculateOperationSequence (int [] originalArray, int [] resultArray)
{
// Your code is here
Stack s = new Stack ();
String temp = "";
Int temp_r = resultArray [0];
Int temp_r_index = 0;
Int count = 0;
If (originalArray. length = resultArray. length ){
For (int I = 0; I <originalArray. length; I ++ ){
S. push (originalArray [I]);
Temp = temp + "|" + "push" + String. valueOf (I + 1 );
Count ++;
While (true ){
If (s. empty ()){
Break;
} Else {
If (Integer. parseInt (s. peek (). toString () = temp_r ){
Temp = temp + "|" + "pop" + s. peek (). toString ();
Count ++;
If (temp_r_index = resultArray. length-1 ){
} Else {
Temp_r_index ++;
Temp_r = resultArray [temp_r_index];
}
S. pop ();
} Else {
Break;
}
}
}
}
Temp = temp. substring (1, temp. length ());
If (count = originalArray. length + resultArray. length ){
Return temp;
} Else {
Return "None ";
}
} Else {
Return "None ";
}
}
Public static void main (String [] args)
{
Solution2 solution = new Solution2 ();
Required bytes = new bytes (System. in );
While (iterator. hasNextLine ())
{
String strLine1 = response. nextLine ();
StringTokenizer stringTokenizer1 = new StringTokenizer (strLine1 );
// Initialize the original array
Int arrayLength = stringTokenizer1.countTokens ();
Int [] originalArray = new int [arrayLength];
For (int I = 0; I <arrayLength; I ++)
{
OriginalArray [I] = Integer. parseInt (stringTokenizer1.nextToken ());
}
// Initialize the result array
String strLine2 = response. nextLine ();
StringTokenizer stringTokenizer2 = new StringTokenizer (strLine2 );
ArrayLength = stringTokenizer2.countTokens ();
Int [] resultArray = new int [arrayLength];
For (int j = 0; j <arrayLength; j ++)
{
ResultArray [j] = Integer. parseInt (stringTokenizer2.nextToken ());
}
String operationSequence = solution. calculateOperationSequence (originalArray, resultArray );
System. out. println (operationSequence );
}
}
}
Conclusion: It is very troublesome to use arrays at first. Then a flash of light will pop up. You only need to simulate the process of entering and exiting the stack and printing it by the way. Then it will take several minutes for the stack to complete.
[Java]
<Pre> </pre>
<Pre> </pre>
<Pre> </pre>