Guest User

Untitled

a guest
Oct 19th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4.  
  5. // Function to check redundant brackets in a
  6. // balanced expression
  7. bool checkRedundancy(string& str)
  8. {
  9. // create a stack of characters
  10. stack<char> st;
  11.  
  12. // Iterate through the given expression
  13. for (auto& ch : str) {
  14.  
  15. // if current character is close parenthesis ')'
  16. if (ch == ')') {
  17. char top = st.top();
  18. st.pop();
  19.  
  20. // If immediate pop have open parenthesis '('
  21. // duplicate brackets found
  22. bool flag = true;
  23.  
  24. while (top != '(') {
  25.  
  26. // Check for operators in expression
  27. if (top == '+' || top == '-' ||
  28. top == '*' || top == '/')
  29. flag = false;
  30.  
  31. // Fetch top element of stack
  32. top = st.top();
  33. st.pop();
  34. }
  35.  
  36. // If operators not found
  37. if (flag == true)
  38. return true;
  39. }
  40.  
  41. else
  42. st.push(ch); // push open parenthesis '(',
  43. // operators and operands to stack
  44. }
  45. return false;
  46. }
  47.  
  48. // Function to check redundant brackets
  49. void findRedundant(string& str)
  50. {
  51. bool ans = checkRedundancy(str);
  52. if (ans == true)
  53. cout << "Yes\n";
  54. else
  55. cout << "No\n";
  56. }
  57.  
  58. // Driver code
  59. int main()
  60. {
  61. string str = "((a+b))";
  62. findRedundant(str);
  63.  
  64. str = "(a+(b)/c)";
  65. findRedundant(str);
  66.  
  67. str = "(a+b*(c-d))";
  68. findRedundant(str);
  69.  
  70. return 0;
  71. }
Add Comment
Please, Sign In to add comment