C++ 程式檢查給定的字串是不是壞的


假設我們有一個包含 n 個字元的字串 S。S 包含小寫英語字母和 ')' 字元。如果字串末尾的 ')' 字元數嚴格大於剩餘字元數,則字串是壞的。我們必須檢查 S 是否是壞的。

因此,如果輸入類似 S = "fega))))))",則輸出將為 True,因為它是壞的,因為有 4 個字母和 6 個 ')'。

步驟

為了解決這個問題,我們將按照以下步驟操作 −

ans := 0
n := size of S
i := n - 1
while (i >= 0 and S[i] is same as ')'), do:
   (decrease i by 1)
z := n - 1 - i
ans := 2 * z - n
if ans > 0, then:
   return true
Otherwise
   return false

示例

讓我們看看以下實現以獲得更好的理解 −

#include <bits/stdc++.h>
using namespace std;

bool solve(string S) {
   int ans = 0;
   int n = S.size();
   int i = n - 1;
   while (i >= 0 && S[i] == ')')
      i--;
   int z = n - 1 - i;
   ans = 2 * z - n;
   if (ans > 0)
      return true;
   else
      return false;
}
int main() {
   string S = "fega))))))";
   cout << solve(S) << endl;
}

輸入

"fega))))))"

輸出

1

更新於:2022-03-03

252 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告