namereq

括弧文字列

Jun 5th, 2018
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <limits.h>
  4. #include <stdbool.h>
  5.  
  6. #define N 10000
  7.  
  8. int count = 0;
  9. int idx = 0; /* スタックが次に入れるところを指す */
  10. int stack[N];
  11.  
  12. int push(){
  13.     count++;
  14.     stack[idx] = count;
  15.     idx++;
  16.     return stack[idx - 1];
  17. }
  18.  
  19. bool stack_is_empty() {
  20.     return (idx == 0) ? true : false;
  21. }
  22.  
  23. int pop(){
  24.     if(stack_is_empty() == true) return INT_MIN;
  25.     int ret = stack[idx - 1];
  26.     idx--;
  27.     return ret;
  28. }
  29.  
  30. int main(void)
  31. {
  32.     char buff[N];
  33.     int i;
  34.  
  35.     printf("括弧文字列を入力して下さい : ");
  36.     fgets(buff, sizeof(buff), stdin);
  37.  
  38.     buff[strlen(buff) - 1] = '\0';        /* 改行コードを消す */
  39.  
  40.     for (i = 0;i < strlen(buff);i++){
  41.         if(buff[i] == '['){
  42.             printf("[");
  43.             int push_val = push();
  44.             printf("%d ", push_val);
  45.         } else if(buff[i] == ']'){
  46.             int pop_val = pop();
  47.             if(pop_val == INT_MIN){
  48.                 printf("\n括弧が整合していません。");
  49.                 return -1;
  50.             }
  51.             printf("]");
  52.             printf("%d ", pop_val);
  53.         }
  54.     }
  55.     if(stack_is_empty() == false){
  56.         printf("\n括弧が整合していません。");
  57.         return -1;
  58.     }
  59.  
  60.     printf("\n括弧は整合していました。");
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment