Leetcode - Stack 문제 풀이 (2개)

숲사람·2022년 5월 5일
0

멘타트 훈련

목록 보기
14/237

Stack Easy 문제 풀이, 풀때마다 순서대로 하단에 추가 됨.

1614. Maximum Nesting Depth of the Parentheses

수식에서 가장 많은 괄호 Depth갯수 구하기.
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/

Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation: Digit 8 is inside of 3 nested parentheses in the string.
char stack[101] = {0,};
int top = 0;
int max_top = 0;

void push(char c)
{
    stack[++top] = c;
    if (top > max_top)
        max_top = top;
}

char pop(void)
{
    return stack[top--];
}

int maxDepth(char * s){
    top = 0;
    max_top = 0;
    memset(stack, 0, sizeof(char) * 101);
    
    while (*s != '\0') {
        if (*s == '(')
            push('(');
        if (*s == ')')
            pop();
        *s++;
    }
    return max_top;
}

20. Valid Parentheses

괄호 표기가 맞는지 확인하는 문제.

Input: s = "()[]{}"
Output: true

Input: s = "(]"
Output: false

https://leetcode.com/problems/valid-parentheses/

struct stack {
    int top;
    char *arr;
    void (*push)(struct stack *, char);
    char (*pop)(struct stack *);
};
struct stack *st;

void cb_push(struct stack *this, char c)
{
    this->arr[++this->top] = c;
}
char cb_pop(struct stack *this)
{
    if (this->top == -1) /* stack is empty */
        return '\0';
    return this->arr[this->top--];
}
struct stack *stack_init(int ssize)
{
    struct stack *s = calloc(1, sizeof(struct stack));
    s->arr = (char *)calloc(ssize, sizeof(char));
    s->top = -1;
    s->push = cb_push;
    s->pop = cb_pop;
    return s;
}

bool isValid(char *s)
{
    int ssize = strlen(s);
    st = stack_init(ssize);
    char tmp = 0;
    
    while (*s != '\0') {
        if (*s == '(' || *s == '{' || *s == '[') {
            st->push(st, *s);
        } else if (*s == ')') {
            tmp = st->pop(st);
            if (tmp != '(' || tmp == '\0')
                return false;
        } else if (*s == '}') {
            tmp = st->pop(st);
            if (tmp != '{' || tmp == '\0')
                return false;
        } else if (*s == ']') {
            tmp = st->pop(st);
            if (tmp != '[' || tmp == '\0')
                return false;
        }
        s++;
    }
    if (st->top == -1)
        return true;
    else
        return false;
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글