解决方案:
i: from 1 to n
j: from 1 to n, used to traverse the sequence seq[1...n]
stack: empty at the beginning
while i <= n || j <= n
IF stack is empty,
push i into stack, i plus 1;
ELSE IF the top of stack is equal to seq[j]
pop from stack, j plus 1;
ELSE IF the top of stack is larger than seq[j]
illegal sequence! Stop here!
ELSE
push i into stack, i plus 1;
legal sequence if the stack is empty!
示例 1:{1, 2, 4, 3},合法序列
In the beginning, i = 1, j = 1, and stack is empty.
1. stack is empty:
stack = {1}, i = 2, j = 1.
2. top of stack 1 is equal to seq[j] = 1:
stack = {}, i = 2, j = 2.
3. stack is empty:
stack = {2}, i = 3, j = 2.
4. top of stack 2 is equal to seq[j] = 2:
stack = {}, i = 3, j = 3.
5. stack is empty:
stack = {3}, i = 4, j = 3.
6. top of stack 3 is smaller than seq[j] = 4:
stack = {3, 4}, i = 5, j = 3.
7. top of stack 4 is equal to seq[j] = 4:
stack = {3}, i = 5, j = 4.
8. top of stack 3 is equal to seq[j] = 3:
stack = {}, i = 5, j = 5.
示例 2:{1, 4, 2, 3},非法序列
In the beginning, i = 1, j = 1, and stack is empty.
1. stack is empty:
stack = {1}, i = 2, j = 1.
2. top of stack 1 is equal to seq[j] = 1:
stack = {}, i = 2, j = 2.
3. stack is empty:
stack = {2}, i = 3, j = 2.
4. top of stack 2 is smaller than seq[j] = 4:
stack = {2, 3}, i = 4, j = 2.
5. top of stack 3 is smaller than seq[j] = 4:
stack = {2, 3, 4}, i = 5, j = 2.
6. top of stack 4 is equal to seq[j] = 4:
stack = {2, 3}, i = 5, j = 3.
7. top of stack 3 is larger than seq[j] = 2:
illegal sequence, stop here.
我正在尽力解释我的想法,希望我已经把事情说清楚了。