您的位置:首页 > 编程语言 > C语言/C++

Leetcode 20. Valid Parentheses

2017-01-15 10:33 375 查看
 20. 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.

Inspired by the stack idea, I use a string (temp) to simulate the function. If met a "(" or "[" or "{" , just append the character to temp, the other characters are“)”."]","}". If met a “)” or "]" or "}",take the last character of temp into compare, as we all
know, the ascii value 40:"(" 41:“)” 91:"[" 93: "]" 123:"{" 125:"}", So if the characters are an valid pair, the absolute difference is less than 2 .if so, just remove the last character of temp, and continue comparing the remaining ones.
class Solution {
public:
bool isValid(string s) {
string temp="";
int i=0;
while(i<s.size())
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
{
temp+=s[i];
i++;
}
else
{
if(temp.size()==0) return false;      // temp is empty, means  “)”,"]","}" has no partners
else if(abs(s[i]-temp[temp.size()-1])<=2) temp=temp.substr(0,temp.size()-1);   //remove the last character of temp
else return false;
i++;
}
}
if(temp.size()!=0) return false;     // temp is not empty, means  "(" or "[" or "{" has been left
else return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++