C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

スタックを使用してバランスの取れた並列処理をチェックするC++プログラム


ここでは、スタックを使用してバランスブラケットをチェックする方法について説明します。開閉ブラケットだけでなく、ブラケットの順番もチェックしています。たとえば、「[{}(){()}]」という表現は正しいと言えますが、「{[}]」という表現は正しくありません。

Input: Some expression with brackets "{()}[]"
Output: They are balanced

アルゴリズム

Step 1: Define a stack to hold brackets
Step 2: Traverse the expression from left to right
Step 2.1: If the character is opening bracket (, or { or [, then push it into stack
Step 2.2: If the character is closing bracket ), } or ] Then pop from stack, and if the popped character is matched with the starting bracket then it is ok. otherwise they are not balanced.
Step 3: After traversal if the starting bracket is present in the stack then it is not balanced.

サンプルコード

#include<iostream>
#include<stack>
using namespace std;
bool isBalanced(string expr) {
   stack<char> s;
   char ch;
   for (int i=0; i<expr.length(); i++) {    //for each character in the expression, check conditions
      if (expr[i]=='('||expr[i]=='['||expr[i]=='{') {    //when it is opening bracket, push into     stack
         s.push(expr[i]);
         continue;
      }
      if (s.empty())    //stack cannot be empty as it is not opening bracket, there must be closing     bracket
         return false;
         switch (expr[i]) {
            case ')':    //for closing parenthesis, pop it and check for braces and square brackets
               ch = s.top();
               s.pop();
               if (ch=='{' || ch=='[')
                  return false;
                  break;
            case '}': //for closing braces, pop it and check for parenthesis and square brackets
               ch = s.top();
               s.pop();
               if (ch=='(' || ch=='[')
                  return false;
                  break;
            case ']': //for closing square bracket, pop it and check for braces and parenthesis
               ch = s.top();
               s.pop();
               if (ch =='(' || ch == '{')
                  return false;
                  break;
         }
      }
      return (s.empty()); //when stack is empty, return true
}
main() {
   string expr = "[{}(){()}]";
   if (isBalanced(expr))
      cout << "Balanced";
   else
      cout << "Not Balanced";
}

出力

Balanced

  1. C++で配列のビットノイズをチェックするプログラム

    N個の整数の配列arr[N]が与えられた場合、タスクは、与えられた配列がバイトニックであるかどうかをチェックすることです。指定されたアレイがバイトニックである場合は、「はい、バイトニックアレイです」と出力します。そうでない場合は、「いいえ、バイトニックアレイではありません」と出力します。 Bitonicアレイとは、アレイが最初に厳密に昇順で、次に厳密に降順である場合です。 この配列のように、arr [] ={1、2、3、4、2、-1、-5}はバイトニック配列です。これは、4までは厳密に昇順であり、4以降は厳密に降順であるためです。 入力 arr[] = {1, 3, 5, 4,

  2. 二分法のためのC++プログラム

    0であり、関数f(x)はaとbの間にある必要があります。つまりf(x)=[a、b ]。タスクは、二分法を使用して、関数f(x)の区間aとbの間にあるルートの値を見つけることです。 二分法とは何ですか? 二分法は、「a」と「b」で定義された指定された制限内の関数f(x)の根の値を見つけるために使用されます。関数の根は、f(a)=0となるような値aとして定義できます。 例 Quadratic equation F(x) =  - 8 This equation is equals to 0 when the value of x will be 2 i.e.  - 8 =