我撰寫了一個函式來檢查某個字串中的括號是否有效,如果有效則回傳 true,否則回傳 false。
例如:
str1: { [ a b ] - ] ( c - d } ] = 假。
str2: { [ a b ] - ( c - d ) } = 真。
當我運行程式時,它沒有給出任何輸出,只是一個空白輸出。
我需要改變什么?
public static Boolean BracketCheck(string str)
{
Stack<char> stk = new Stack<char>();
Stack<char> aid = new Stack<char>();
Stack<char> temp = new Stack<char>();
while (str != "")
{
char ch = str[0];
if(ch == '(' || ch == '{' || ch == '[' || ch == ')' || ch == '}' || ch == ']')
{
stk.Push(ch);
}
if(str.Length != 1)
str = str.Substring(1, str.Length - 1);
}
stk = Opposite(stk);
char first = stk.Pop();
char last;
while (!stk.IsEmpty() && !aid.IsEmpty())
{
while (!stk.IsEmpty())
{
aid.Push(stk.Top());
last = stk.Pop();
if (stk.IsEmpty())
if (int.Parse(first "") 1 != int.Parse(last "") || int.Parse(first "") 2 != int.Parse(last ""))
{
return false;
}
}
first = aid.Pop();
while (!aid.IsEmpty())
{
aid.Push(aid.Top());
last = aid.Pop();
if (aid.IsEmpty())
if (int.Parse(first "") 1 != int.Parse(last "") || int.Parse(first "") 2 != int.Parse(last ""))
{
return false;
}
}
first = stk.Pop();
}
return true;
}
public static Stack<char> Opposite(Stack<char> stk)
{
Stack<char> temp = new Stack<char>();
while (stk.IsEmpty())
{
temp.Push(stk.Pop());
}
return temp;
}
uj5u.com熱心網友回復:
你是在正確的方式 ( Stack) 但它應該只是一個,而不是三個。僅檢查括號有效性:
public static Boolean BracketCheck(string str) {
if (string.IsNullOrEmpty(str))
return true;
Stack<char> expected = new Stack<char>();
foreach (char c in str) {
if (c == '(')
expected.Push(')');
else if (c == '[')
expected.Push(']');
else if (c == '{')
expected.Push('}');
else if (c == ')' || c == ']' || c == '}') {
if (expected.Count == 0 || expected.Pop() != c)
return false;
}
}
return expected.Count == 0;
}
如果您想將字串驗證為公式,例如(3 ) 5有有效的括號,但公式無效,請查看調車場演算法
uj5u.com熱心網友回復:
您在該行之前創建aid并沒有對其進行任何操作,while (!stk.IsEmpty() && !aid.IsEmpty())因此輔助是空的,并且該回圈中的任何內容都不會運行。
在代碼審查網站上可能會更好地詢問一些事情;例如,您不需要從字串中洗掉字符來迭代其中的字符或將字符轉換為字串到整數來比較它們。基本上你想要做的是創建一個堆疊,遍歷字串,任何左括號推入堆疊,任何右括號彈出堆疊并檢查左括號匹配,如果在字串的末尾堆疊為空,那么它是有效的。您不需要所有的反轉和創建第二個堆疊的東西。
uj5u.com熱心網友回復:
這對我有用你有什么問題或需要改進的地方嗎?
public static Boolean BracketCheck(string str)
{
Stack<char> stk = new Stack<char>();
foreach(char c in str)
{
if (c == '(' || c == '[' || c == '{')
{
stk.Push(c);
}
else if (c == ')' || c == ']' || c == '}')
{
if (stk.Top() == (int)c - 1 || stk.Top() == (int)c - 2)
{
stk.Pop();
}
}
}
return stk.IsEmpty();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/527839.html
下一篇:ISBN格式無法寫入輸出
