给定一个字符串所表示的括号序列,包含以下字符: '(', ')'
, 判定是否是有效的括号序列。
括号必须依照 "()"
顺序表示, "()"
是有效的括号,但 ")("
则是无效的括号。
/**
* @param string: A string
* @return: whether the string is valid
*/
bool match_parentheses(char* string) {
//方法一:
// int len = strlen(string);
// if(string[0] == '(' && string[len - 1] == ')' && len % 2 == 0){
// return 1;
// }
// return 0;
//方法二:
int count = 0;
if(string[0] == '('){
count++;
for(int i = 1; string[i] != '\0'; i++){
if(string[i] == '('){
count++;
}
else{
count--;
}
}
return count == 0;
}
else{
return 0;
}
}