Tucancitto

Lab2 - Pb2

Apr 6th, 2021 (edited)
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <cstring>
  4. #include <vector>
  5.  
  6. void Citire(std::vector<char>& sir)
  7. {
  8.     std::ifstream fin("parantezare.in");
  9.     char p;
  10.     while (fin >> p)
  11.     {
  12.         if (p == ' ')
  13.             continue;
  14.         else
  15.             sir.push_back(p);
  16.     }
  17.  
  18.     fin.close();
  19. }
  20.  
  21. void Afisare(std::vector<char> sir)
  22. {
  23.     for (auto c : sir)
  24.         std::cout << c;
  25. }
  26.  
  27. int Ordin(char c)
  28. {
  29.     if (c == '(' or c == ')')
  30.         return 0;
  31.     if (c == '[' or c == ']')
  32.         return 1;
  33.  
  34.     return 2;
  35. }
  36.  
  37. bool Parantezare(std::vector<char> paranteze)
  38. {
  39.     std::vector<char> deschise;
  40.  
  41.     for (auto& crt : paranteze)
  42.     {
  43.         auto urm = *(&crt + 1);
  44.         if (crt == '{' && urm == '}' || crt == '[' && urm == ']')
  45.             return 0;
  46.  
  47.         if (strchr("([{", crt))
  48.             deschise.push_back(crt);
  49.         else
  50.         {
  51.             if (!deschise.empty())
  52.             {
  53.                 for (auto des = deschise.begin(); des != deschise.end() - 1; ++des)
  54.                 {
  55.                     if (Ordin(crt) >= Ordin(*des))
  56.                         return 0;
  57.                 }
  58.  
  59.                 if (crt == ')' && deschise.back() == '(' || crt == ']' && deschise.back() == '[' || crt == '}' && deschise.back() == '{')
  60.                     deschise.pop_back();
  61.                 else
  62.                     return 0;
  63.             }
  64.             else
  65.                 return 0;
  66.         }
  67.     }
  68.     return deschise.empty();
  69. }
  70.  
  71. int main()
  72. {
  73.     std::vector<char> paranteze;
  74.     Citire(paranteze);
  75.  
  76.     if (!paranteze.empty())
  77.     {
  78.         std::cout << "Sirul ";
  79.         Afisare(paranteze);
  80.  
  81.         if (Parantezare(paranteze))
  82.             std::cout << " este corect. ";
  83.         else
  84.             std::cout << " nu este corect. ";
  85.     }
  86.     else
  87.         std::cout << "Sirul este vid. ";
  88.  
  89.     paranteze.clear();
  90.     paranteze.shrink_to_fit();
  91.     return 0;
  92. }
  93.  
Add Comment
Please, Sign In to add comment