LeetCode第20题
题目描述:
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
思路
立马想到用栈来做。没啥讲的,直接上代码。
源代码
bool isValid(char * s){
//用栈来做
/*ASCII码:
(:40
):41
[:91
]:93
{:123
}:125
*/
int len = strlen(s);
if(len == 0)
return true;
char result[len];
int top = -1; //栈顶,初始值为-1
for(int i = 0;i < len;++i){
if(top == -1)
result[++top] = s[i]; //入栈
else{
if((s[i]-result[top])==1 || (s[i]-result[top])==2){
--top; //若符合匹配,则出栈
}
else{
result[++top] = s[i]; //入栈
}
}
}
if(top == -1)
return true;
else
return false;
}
分析
关键点在于两个括号是否匹配的判断和当栈顶已经到底时的处理。
时间复杂度为线性级别,空间复杂度也为线性级别(因为要开辟一个数组作为栈)。
网友评论