Advertisement
madalinaradu

P13 - inchidere paranteze

Apr 27th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. /** sa se verifice daa intr-o expresie parantezele se inchid corect: ex: (ab[c]d){e} */
  2.  
  3. #include <iostream>
  4. #include <stack>
  5. #include <string.h>
  6. using namespace std;
  7.  
  8. /** verifica daca o parenteza deschisa coincide cu una inchisa de acelasi tip*/
  9. bool estePereche(char deschis, char inchis){
  10.     if (deschis == '(' && inchis == ')')
  11.         return true;
  12.     if (deschis == '[' && inchis == ']')
  13.         return true;
  14.     if (deschis == '{' && inchis == '}')
  15.         return true;
  16.  
  17.     return false;
  18. }
  19.  
  20. bool verificaParanteze(char *s){
  21.     // stiva folosita in care vom insera parantezele
  22.     stack<char> stiva;
  23.     char c;
  24.     int i;
  25.  
  26.     for(i=0;i<strlen(s);i++){
  27.         if (s[i] == '(' || s[i] == '[' || s[i] == '{'){
  28.            //parantezele deschise le pun in stiva
  29.            stiva.push(s[i]);
  30.         } else  if (s[i] == ')' || s[i] == ']' || s[i] == '}'){
  31.             //Daca e o paranteza inchisa extrag elementul din varful stivei si verificam daca e pereche.
  32.             if (stiva.empty()){
  33.                 //am gasit o paranteza inchisa si in stiva nu am nimic
  34.                 return false;
  35.             } else {
  36.                 c= stiva.top(); //iau elementul din varful stivei
  37.                 stiva.pop();//elimina elementul din varful stivei
  38.                 if(!estePereche(c,s[i])){
  39.                     return false;
  40.                 }
  41.             }
  42.         }
  43.     }
  44.     if (stiva.empty())
  45.         return true;
  46.     else
  47.         return false;
  48.  
  49. }
  50.  
  51. int main(){
  52.     char expresie[100];
  53.     cout<<"Dati expresia cu paranteze:";
  54.     cin>>expresie;
  55.     if (verificaParanteze(expresie)){
  56.         cout<<"Expresia " << expresie << " e valida";
  57.     } else {
  58.         cout<<"Expresia " << expresie << " e invalida";
  59.     }
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement