判斷字串中的括號是否匹配
阿新 • • 發佈:2021-06-11
@
目錄1、判斷括號是否匹配(只有小括號())
1.1、不成功版,只判斷了括號數量是否相等
題目:給你一個字串,判斷字串中的括號是否匹配,意思就是一個左括號要對應一個右括號,即'('
和')'
必須成對出現。那不就是判斷字串裡面的'('
和')'
數量是不是相等嗎,這個簡單呀,用stl演算法裡面的count()
函式;開擼
#include<iostream> #include<string> #include <algorithm> using std::endl; using std::cin; using std::cout; using std::string; using std::count; int main() { string input; getline(cin, input); int leftParenthesisNumber = 0, rightParenthesisNumber = 0; leftParenthesisNumber = count(input.begin(), input.end(), '('); rightParenthesisNumber = count(input.begin(), input.end(), ')'); if (leftParenthesisNumber == rightParenthesisNumber) { cout << "YES" << endl; }else { cout << "NO" << endl; } return 0; }
然後一看,部分通過。錯誤用例((1+2)+1))(
,enmmm。一看就曉得出啥問題了,左括號和右括號數量是匹配了可是位置不對呀。看來要換種方法了。
1.2、成功版,真正判斷了括號是否匹配(位置和數量)
#include<iostream> #include<string> #include <algorithm> using std::endl; using std::cin; using std::cout; using std::string; using std::count; int main() { string input; getline(cin, input); int num=0; for (int i = 0; i < input.length(); i++) { if (input[i] == '(') { num++; }else if (input[i] == ')') { num--; } if (num < 0) { //num<0 說明出現右括號數量大於左括號了,位置不匹配。直接不合格輸出 NO cout << "NO" << endl; break; } } if (num == 0) { cout << "YES" << endl; }else if (num > 0) { //num>0 說明出現右括號數量小於左括號了,數量不匹配 輸出 NO cout << "NO" << endl; } return 0; }
基本思想是從開頭往後找,找到一個左括號,括號數加一,找到一個右括號,認為可以對消一對括號,即括號數減一。一旦有括號數小於0,則代表找到這個位置右括號數量大於左括號了,肯定不對了,直接完成搜尋。如果找到最後都沒有括號數小於0的情況,那麼看括號數是多少,為0 說明左右正好對消,滿足條件,大於0,說明左括號多了,不滿足情況。
2、字串中有三種括號 ‘(’,’)’,’{’,’}’,’[’,’]’時的判斷(利用棧)
假如括號字串中有 '(',')','{','}','[',']' 來判斷是否是有效括號。左括號必須用相同型別的右括號閉合。左括號必須以正確的順序閉合。
bool isValid(string s) { stack<char> myStack; for(int i=0;i<s.size();i++){ if(isLeftParenthesis(s[i])){ //判斷這個字元是不是左括號,保證棧裡面全是左括號 myStack.push(s[i]); } else{ //到這兒,這個括號已經是右括號了 if(myStack.empty() || (myStack.top()!=s[i]-1 && myStack.top()!=s[i]-2)){ /*這個括號已經是右括號了,而且棧裡面都空了,那肯定不匹配(因為沒有右括號開頭的括號嘛) 那如果棧沒空,那麼就要判斷棧頂的左括號和現在這個右括號是否匹配了 ‘(’與‘)’ASCII值差1,'['與']ASCII值差2,'{'與'}'ASCII值也差2*/ return false; } myStack.pop(); } } return myStack.empty(); } bool isLeftParenthesis(char c){ //判斷是不是左括號 return (c=='('||c=='['||c=='{'); }