λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
🐍 Algorithm/μ•Œκ³ λ¦¬μ¦˜-Python

[μ•Œκ³ λ¦¬μ¦˜] Day1 - κ΄„ν˜Έ

by Danna 2018. 8. 4.
728x90
728x90
01 문제

02 μ•Œκ³ λ¦¬μ¦˜
  • μž…λ ₯된 λ¬Έμžμ—΄μ„ μŠ€νƒμ— push, pop ν•˜λ©΄μ„œ κ΄„ν˜Έμ˜ 짝이 λ§žλŠ”μ§€ ν™•μΈν•œλ‹€.
  • λ¬Έμžμ—΄μ—μ„œ β€˜(β€˜ 일 λ•Œ pushν•œ νšŸμˆ˜μ™€ β€˜)’일 λ•Œ popν•œ νšŸμˆ˜κ°€ κ°™μ•„μ•Ό ν•œλ‹€.
  • is_empty ν•¨μˆ˜λ₯Ό μ΄μš©ν•΄ pushν•œ 게 λ‹€ pop λ˜μ—ˆλŠ”μ§€ λΉ„κ΅ν•˜λŠ”λ°,  pop을 더  λ§Žμ΄ ν•˜λŠ” κ²½μš°λ„ κ³ λ €ν•΄μ£Όμ–΄μ•Ό ν•˜λ―€λ‘œ stackμ—μ„œ popν•  μš”μ†Œκ°€ 없을  κ²½μš°μ— vps = -1둜 ν•΄μ£Όκ³ , 이 값이 μ΄ˆκΈ°κ°’κ³Ό 같은지 비ꡐ함.

03 μ½”λ“œ

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 100
 
typedef struct array_stack
{
        int arr[LEN];
        int top;
}array_stack;
 
void stack_init(array_stack *pstack);
void push(array_stack *pstack, int x);
void pop(array_stack *pstack);
void size(array_stack *pstack);
int is_empty(array_stack *pstack);
void top(array_stack *pstack);
int vps;
 
int main(void)
{
        int i, size, num;
        char str[50];
        array_stack stack;
 
        scanf("%d", &num);
        getchar();
 
        while (num--)
        {
                 scanf("%s", str);
                 size = strlen(str);
                 stack_init(&stack);
                 for (i = 0; i < size; i++)
                 {
                         if (str[i] == '(')
                                 push(&stack, i);
                         else if (str[i] == ')')
                                 pop(&stack);
                 }
                 if (is_empty(&stack) == 1 && vps == 0)
                         printf("YES\n");
                 else
                         printf("NO\n");
        }
}
void stack_init(array_stack *pstack)
{
        vps = 0;
        pstack->top = -1;
}
void push(array_stack *pstack, int x)
{
//      vps = 0;
        ++pstack->top;
        pstack->arr[pstack->top] = x;
}
void pop(array_stack *pstack)
{
        if (pstack->top == -1)
                 vps = -1;
        else
                 pstack->top--;
}
void size(array_stack *pstack)
{
        printf("%d\n", pstack->top + 1);
}
int is_empty(array_stack *pstack)
{
        if (pstack->top == -1)
                 return 1;
        else
                 return 0;
}
void top(array_stack *pstack)
{
        if (pstack->top == -1)
                 printf("-1\n");
        else
                 printf("%d\n", pstack->arr[pstack->top]);
}
 



728x90
728x90