problem
basics
Stack
A special data structure in a linear table in which data can only be inserted or deleted from a fixed end and the other end is blocked
The main characteristic of Stack is First In Last Out
Stack overflows when full, and underflows when empty
Overflow: When the stack is already full of data elements, the stack storage will error if it continues to deposit data into the stack.
Uderflow: When the stack is empty, the stack will continue to fetch data
Two kinds of algorithm
PUSH and POP
RC
```bash
Status InitStack(SqStack &S){
S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType))
if(!S.base) exit(OVERFLOW)
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack &S, SElemType &e){
if(S.top - S.base >= S.stacksize){ //栈满,追加存储空间
S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));
if(!S.base) exit(OVERFLOW); //存储分配失败
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
* S.top++ = e;
return OK;
}
Status Pop(SqStack &S, SElemType &e){
if(S.top == S.base) return ERROR;
e = * --S.top;
return OK;
}
Analysis Process
1.Initialize stack S
2.Process each bracket of the expression once
3.If an open bracket is encountered, we simply push it onto the stack
4.If we encounter a close bracket, then we check the top of the stack if the top of the stack is an open bracket of the same type, then we pop it off the stack and continue processing ,otherwise, the expression is invalid
5.If we still have elements in the stack at the end, that means the expression is invalid
Code
func isValid(s string) bool {
if s == "" {
return true
} // Empty strings are valid by default
if len(s)%2 == 1 {
return false
} // An odd number of parentheses will not match
keyMap := map[string]string{
"}": "{",
"]": "[",
")": "(",
} //Establish correspondence
var stack []string
for i := 0; i < len(s); i++ {
if len(stack) > 0 {
tmp, ok := keyMap[string(s[i])] // The stack is not empty
if ok {
top := stack[len(stack)-1] // The current element is the right half bracket
// If the mapping to the element currently traversed is the same as the bracket at the top of the stack
if top == tmp {
// pop
stack = stack[:len(table)-1]
// skip this loop
continue
}
}
}
// Empty stack or no match, add stack
stack = append(stack, string(s[i]))
}
// If the last stack is empty, it all matches, and returns true
return len(stack) == 0
}