您的位置:首页 > 职场人生

Valid Parentheses

2015-07-18 11:24 274 查看
题目:

       

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.

题意:给定一个字符串,里面只包含
'('
')'
'{'
'}'
'['
 and 
']'
几种字符,
"()"
 and 
"()[]{}"
 几种字符串都是合法的,而
"(]"
 and 
"([)]"
 字符串都是非法的,所以现在给定一个字符串判定是否合法。


解题思路:

      1.首先判断字符串的长度,如果是奇数,直接返回false;

      2.循环判断相邻字符是否为一个匹配项:(1)如果相邻字符匹配,即s[i]和s[i+1]是否匹配,若匹配则跳过这两个字符,i=i+2;

                                                                    (2)如果相邻字符不匹配,则将第一个字符存储s[i]到一个新的字符串tem中,i++;

       3.循环判定tem,如果tem长度最后保持不变,则说明里面字符不匹配,返回false,如果tem长度最后为0,则表示全匹配上,返回true。

代码:

     
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Valid Parentheses 面试