2016-06-08 112 views
-3

檢查inputlikelike []),[])等,它給運行時錯誤,但對於其他輸入如[[]],它工作正常。運行時錯誤的平衡括號

class Solution { 
public: 
bool isValid(string s) 
{ 
    stack<char> st; 
    int i=0; 
    char top; 
    if(s[0] == ']' || s[0] == ')' || s[0] == '}') 
     return 0; 
    while(s[i]!='\0') 
    { 

     if(s[i] == '[' || s[i] == '(' || s[i] == '{') 
      { 

       st.push(s[i]); 
       i++; 
       continue; 
      } 

     else if(st.top() == '(' && s[i] == ')') 
      { 
       st.pop(); 
       i++; 
       continue; 
      } 

     else if(st.top() == '{' && s[i] == '}') 
      { 
       st.pop(); 
       i++; 
       continue; 
      } 

     else if(st.top() == '[' && s[i] == ']') 
      { 
       st.pop(); 
       i++; 
       continue; 
      } 
     else 
      { 
       st.push(s[i]); 
       i++; 
       continue; 
      } 

    } 
    if(st.empty()) 
     return 1; 
    else 
     return 0; 
} 
}; 
+0

嘗試重述你的問題,我不明白你在問什麼,確保你有adde d正確的標籤 – Jerzyk

+0

我得到運行時錯誤輸入「[]))」但它應該返回false而不是。 –

+0

看起來你在下面得到了一個有用的答案,但沒有迴應。請注意,像Stack Overflow這樣的網站完全是基於社區的好感,所以請儘量鼓勵它與互動和投票儘可能多的集合。 – halfer

回答

0

我不知道你在寫這段代碼的語言是什麼,它很不清楚你想實現什麼。

花一分鐘時間瀏覽你的代碼,我可以推斷,你在這裏有一個函數,用來檢查你是否有有效的圓括號(可能有任何{}()[]的組合,除非它們不交叉其他。

那麼,爲什麼你的代碼不能正常工作?因爲你正在堆棧呼叫時棧是空的。

所以讓我們嘗試重寫代碼...

int i = 0; 

while(s[i] != '\0') { 

    if (s[i] == '[' || s[0] == '(' || s[0] == '{') { 
     /* push every opening bracket to the stack */ 
     st.push(s[i]); 
    } else if (s[i] == ']' || s[i] == ')' || s[i] == '}') { 
     /* now we got closing bracket */ 
     if (st.empty()) { 
      /* let's check if stack is empty - this may happen in 2 cases: 
       - closing bracket as first character 
       - this is errorneus bracket 
      */ 
      return 0; 
     } else { 
      /* stack is not empty - this part of the code could be 
       put in first "if" part, but I do not know how expensive 
       is access to the stack, so for code clarity and 
       possible performance gain - leaving it here  

       so we get char from the top of the stack 
      */ 

      char top = st.pop(); 
      if (not ((top == '(' and s[i] == ')') || 
         (top == '[' and s[i] == ']') || 
         (top == '{' and s[i] == '}'))) { 
       return 0 
      } 
     } 
    } 
    i++; 
} 
return st.is_empty()