2016-06-08 62 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()