/*****************************************************问题描述*************************************************
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
判断输入的字符串是否合法,这个有点算法思想的味道了
/*****************************************************我的解答*************************************************
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s)
{
//用数组模拟栈操作,当前字符是'(','[','{'时执行压栈操作,否则执行出栈操作并比较
var stack = [];
var strToArr = s.split('');
for(var currentStr in strToArr)
{
if(strToArr[currentStr] == '(' || strToArr[currentStr] == '[' || strToArr[currentStr] == '{')
{
stack.push(strToArr[currentStr]);
console.log('push string:' + strToArr[currentStr]);
}
else
{
switch(strToArr[currentStr])
{
case ')':
{
if('(' != stack.pop())
{
return false;
}
else
{
break;
}
}
case ']':
{
if('[' != stack.pop())
{
return false;
}
else
{
break;
}
}
case '}':
{
if('{' != stack.pop())
{
return false;
}
else
{
break;
}
}
}
}
}
return stack.length == 0;
};
console.log(isValid('{[]}'));
leetCode刷题记录6_20_Valid Parentheses
最新推荐文章于 2022-06-08 14:09:40 发布