喜歡的朋友可以關注收藏一下: http://blog.csdn.NET/qq_31201973
本文如有錯誤,請及時私信我。
原版要求:
如果給你一個字符串,它只包含下面的幾個字符:’(‘、’)’、’{‘、’} ’、’[’、‘]’,你需要判斷輸入的字符串是否是一個有效的圓括號字符串。例如“((([[]])))”是有效的,但是“{}”和“((”則不是。
提示:根據經驗,必須選用一種最合適的STL容器來完成該題,必須寫上測試代碼。
解題分析:比較明顯的是,爲了判斷有效,我們必須從頭掃描整個字符串,問題在於我們不能立即判斷,因爲當前節點依賴後續節點,因此我們需要將棧作爲輔助工具。
具體操作爲:如果是左括號入棧,直到讀到所依賴的右括號,再從棧中彈出該節點,如果當前節點是右括號,則棧頂必須是相依賴的左括號,否則輸入無效。當掃描完全部,棧應該爲空,否則無效。
假設在表達式中,([]())或[([ ][ ])],等爲正確的格式,[( ])或([( ))或 (()]) 均爲不正確的格式。
則 檢驗括號是否匹配的方法可用“期待的急迫程度”這個概念來描述。
例如:考慮下列括號序列:
[ ( [ ] [ ] ) ]
1 2 3 4 5 6 7 8
分析可能出現的不匹配的情況:
•到來的右括弧並非是所“期待”的;
•到來的是“不速之客”;
•直到結束,也沒有到來所“期待”的括弧。
算法的設計思想:
1.凡是出現左括弧,則進棧。
2.凡是出現右括弧,首先檢查棧是否爲空,若爲空,則表明右括號是多餘的。否則與棧頂元素比較,若相配左括號出棧,否則表明不相配。
3.表達式檢驗結束時,若棧空則表明表達式中匹配正確,否則則表明左括號多餘,表示不相配。
僞算法:
這個算法主要採取了棧的方式,之前採取了stack+string的模式,結果stack的push抽了,只能傳地址,導致出現越界問題。
越界就導致判斷的不匹配,所以我用char*+stack的結果,並且定義一個char截取除了首元素的部分,使其匹配。
代碼:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<stack>
#include<cstring>
using namespace std;
const int OK = 1;
const int NO = 0;
int Parentheses_matching_detection(char* s)
{
stack<char> sta;
char s1;
int i = 0;
int state = 1; //1爲合法 0爲不合法
while ((i < strlen(s)) && state)
{
switch (s[i])
{
case '(':
{
sta.push(s[i]);
++i;
break;
}
case ')':
{
s1 = sta.top();
if ((!sta.empty()) && (s1 == '('))
{
sta.pop();
++i;
break;
}
else
{
state = 0;
break;
}
}
case '(':
{
sta.push(s[i]);
++i;
break;
}
case ')':
{
s1 = sta.top();
if ((!sta.empty()) && (s1 == '('))
{
sta.pop();
++i;
break;
}
else
{
state = 0;
break;
}
}
case '{':
{
sta.push(s[i]);
++i;
break;
}
case '}':
{
s1 = sta.top();
if ((!sta.empty()) && (s1 == '{'))
{
sta.pop();
++i;
break;
}
else
{
state = 0;
break;
}
}
case '[':
{
sta.push(s[i]);
++i;
break;
}
case ']':
{
s1 = sta.top();
if ((!sta.empty()) && (s1 == '['))
{
sta.pop();
++i;
break;
}
else
{
state = 0;
break;
}
}
defaule:
{
++i;
break;
}
}
}
if (sta.empty() && state)
{
return OK;
}
else
{
return NO;
}
}
int main()
{
char a = 'a';
char *s = &a;
while (1)
{
cout << "請輸入一組字符:";
gets(s);
if (Parentheses_matching_detection(s))
{
cout << "字符串中 無 不匹配的括號." << endl;
}
else
{
cout << "字符串中 有 不匹配的括號." << endl;
}
}
system("pause");
return 0;
}
運行截圖: