Valid Parentheses

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.

将左括号压入数组,然后遇到右括号时就与数组中的最后一个元素比较,匹配则继续下一个元素,不匹配输出false,直到所有的元素都执行一遍,期间如果遇到右括号时数组为空,则输出false,最后看数组的元素是否为0,是则输出true,否则输出false。

bool isValid(char *s) {

    char c[100];
    int index = 0;
    for(int i = 0; i<strlen(s); i++){
        if(s[i] == '(' || s[i] == '[' || s[i] == '{') c[index++] = s[i];
        if(s[i] == ')' || s[i] == ']' || s[i] == '}'){
            if(index == 0) return false;
            char r = c[index-1];
            switch(s[i]){
                case ')':
                if(r == '(') index--;
                else return false;
                break;
                case ']':
                if(r == '[') index--;
                else return false;
                break;
                case '}':
                if(r == '{') index--;
                else return false;
                break;
            }
        }
        
    }
    if(index == 0){
        return true;
    }
    else{
        return false;
    }
}

 

posted @ 2015-03-24 19:39  hongchun_z  阅读(116)  评论(0编辑  收藏  举报