20.有效的括号

20.有效的括号_第1张图片
20.有效的括号_第2张图片
思路:顺序栈,遍历

bool isValid(char * s)
{
    if(*s == 0)
        return true;
    int len = strlen(s);
    if(len & 1) 
        return false;
    char stack[len];
    int top = -1;
    for(int i=0; i<len; ++i)
    {
        if(s[i] == '(' || s[i] == '[' || s[i] == '{')
            stack[++top] = s[i];
        else if(top == -1) 
            return false;
        else if(s[i] == stack[top]+1 || s[i] == stack[top]+2)
            stack[top--] = 0;
        else return false;
        }
    return top == -1;
}
public class Solution {
    public bool IsValid(string s) 
    {
        if(s.Length == 0)
            return true;
        if(s.Length % 2 != 0)
            return false;

        Stack<char> stack = new Stack<char>();
        bool flag = false;
        foreach(char c in s)
        {
            if(c == '(' || c == '{' || c == '[' )
                stack.Push(c);
            if((c == ')' || c == '}' || c == ']')  && stack.Count != 0)
            {
                switch(c)
                {
                    case ')' :
                    if(stack.Peek() == '(')
                    {
                        stack.Pop();
                        flag = true;
                    }
                    else
                    {
                        return false;
                    }
                    break;
                    case '}' :
                    if(stack.Peek() == '{')
                    {
                        stack.Pop();
                        flag = true;
                    }
                    else
                    {
                        return false;
                    }
                    break;
                    case ']' :
                    if(stack.Peek() == '[')
                    {
                        stack.Pop();
                        flag = true;
                    }
                    else
                    {
                        return false;
                    }
                    break;
                }
            }
        }
        if(stack.Count != 0)
            flag = false;
        return flag;

    }
}

你可能感兴趣的:(20.有效的括号)