Valid Parentheses

来源:互联网 发布:gta5捏脸数据日本妹子 编辑:程序博客网 时间:2024/04/30 06:00

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

此题难度不大,是基本的思路。右边字符是要匹配消掉的。左边是存入的!所以重点在右边字符!

bool isValid(string s) {        int i = 0;        int index = 0;        string right_str = ")}]";        string left_str  = "({[";        stack<char> my_stack;                while(s[i] != '\0')        {             if((index=right_str.find(s[i])) >= 0)             {                 if(my_stack.empty())                 {                    return false;                 }                 else                 {                     //另一种非索引方式                     //if((my_stack.top() == '('&&s[i]==')')||(my_stack.top() == '{'&&s[i]=='}')||(my_stack.top() == '['&&s[i]==']'))                      if(my_stack.top() == left_str[index])                            my_stack.pop();                      else                        return false;                 }             }             else             {                my_stack.push(s[i]);             }                            i++;        }             return my_stack.empty();    }


0 0
原创粉丝点击