Advertisement
Cinestra

Validating Postfix (I need to validate prefix)

Mar 28th, 2023
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. bool validate(const string& postfix)
  2. {
  3. /*
  4. A postfix expression is valid if and only if:
  5. 1) The first two elements are operands(values), and
  6. 2) The last element is an operator, and
  7. 3) For every n values there are n-1 operator(s), and
  8. */
  9.  
  10. // The NOT character messes things up a lot for whatever reason
  11. // The NOT character can be the second element
  12. // And there can be an infinite number of not elements while only one character
  13.  
  14. char first_element = postfix[0];
  15. char second_element = postfix[1];
  16. char last_element = postfix[postfix.size() - 1];
  17.  
  18.  
  19. if (priority(first_element) != 0)
  20. return false;
  21.  
  22. if (priority(second_element == 2) || priority(second_element) == 3)
  23. return false;
  24.  
  25. int num_letters = 0;
  26. int non_not_operands = 0;
  27.  
  28. for (int i = 0; i < postfix.size(); i++)
  29. {
  30. if (priority(postfix[i]) == 0 && postfix[i] != ' ')
  31. num_letters++;
  32. else if (priority(postfix[i]) == 2 || priority(postfix[i] == 3))
  33. non_not_operands++;
  34. }
  35.  
  36. return (num_letters == (non_not_operands + 1));
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement