思路比较简单,就是栈的应用
但有几个坑点:
1. 在判断过程中,获取栈top元素时,需要先判断是否为空
2. 结束返回时,注意判断是不是遍历了整个string(以防类似于这种情况"{}]]")
class Solution {
public:
bool isValid(string s) {
std::stack<char> leftParenthese;
char tmpChar = 0;
int index = 0;
for (index = 0; index < s.length(); ++index) {
tmpChar = s.at(index);
if ('(' == tmpChar || '{' == tmpChar || '[' == tmpChar) {
leftParenthese.push(tmpChar);
} else if (')' == tmpChar) {
if (leftParenthese.empty() || '(' != leftParenthese.top())
break;
else
leftParenthese.pop();
} else if ('}' == tmpChar) {
if (leftParenthese.empty() || '{' != leftParenthese.top())
break;
else
leftParenthese.pop();
} else if (']' == tmpChar) {
if (leftParenthese.empty() || '[' != leftParenthese.top())
break;
else
leftParenthese.pop();
}
}
return leftParenthese.empty() && index == s.length();
}
};
优化点:
1. 那么多if看着闹心,switch中break又不能直接跳出for循环
2. map又大材小用
3. for循环中使用s.length()太耗时!!!!(从4ms到0ms,100%,内存是8.4M,96.12%)
class Solution {
public:
bool isValid(string s) {
std::stack<char> leftParenthese;
char tmpChar = 0;
char tmpArray[256] = {0};
tmpArray[')'] = '(';
tmpArray[']'] = '[';
tmpArray['}'] = '{';
int index = 0;
int sLength = s.length();
for (index = 0; index < sLength; ++index) {
tmpChar = s.at(index);
if ('(' == tmpChar || '{' == tmpChar || '[' == tmpChar) {
leftParenthese.push(tmpChar);
} else if (leftParenthese.empty()) {
break;
} else if (tmpArray[tmpChar] != leftParenthese.top()){
break;
} else {
leftParenthese.pop();
}
}
return leftParenthese.empty() && index == sLength;
}
};