2016年2月19日 星期五

LEET code -- 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.


用stack就可以了
如果stack 的頭 不是相對應的左括弧 就是錯的




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
bool isValid(char* s) {
    int size=256;
    char *stack=calloc(size,sizeof(char));
    int stackHead=0;
    
    for(;*s;s++){
        if(*s=='(' || *s=='{' || *s=='['){
            stack[stackHead++]=*s;
        }else{
            if(*s==')'){
                if(stack[--stackHead]!='(')return false;
            }else if(*s=='}'){
                if(stack[--stackHead]!='{')return false;
            }else if(*s==']'){
                if(stack[--stackHead]!='[')return false;
            }
        }
        if (stackHead >= size*0.8){
            stack=realloc(stack,sizeof(char)*size*2);
            size*=2;
        }
    }
    
    return stackHead==0? true:false;
}




沒有留言:

張貼留言