【数据结构】-括号匹配
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                【数据结构】-括号匹配
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                問題:
輸入一個帶有 '(' 、')'的字符串,編寫程序判斷左右括號個數(shù)是否匹配。
輸入:(4+3)*5/((34+2)-64)?
思路:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?|? 若有左括號壓入棧中
輸入字符串--->遍歷各字符--->? ?|? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??--->判斷棧是否為空--->空--->匹配
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?|? 若有右括號進入判斷--->棧為空--->括號不匹配? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??--->不空--->不匹配
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? --->棧不空--->將棧頂彈出
?
c++代碼:
#include<stack> #include<string> #include<iostream>using namespace std; bool matchParenthesis(const string& s) {stack<char> let;string::size_type len = s.length();for(string::size_type i=0;i<len;i++){char a = s.at(i);if(a=='(')let.push(a);else if(a==')'){if(let.empty()){cout<<"false"<<endl;return false;}let.pop();}}if(let.empty()){cout<<"true"<<endl;return true;} else{cout<<"false"<<endl;return false;} } int main(void) {string s;cout<<"please input string:";cin>>s;matchParenthesis(s); }?
總結(jié)
以上是生活随笔為你收集整理的【数据结构】-括号匹配的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: infoseccrypto_java下载
- 下一篇: matlab定义域为全体实数画图,MAT
