题目相关
【题目解读】
检查输入的括号字符串中的括号是否匹配
【原题描述】原题链接
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
【难度】Easy
Solution
括号匹配问题,可以采用栈的方式进行判断。
如果遇到"{"、"["、"(“的情况入栈,如果是”}"、"]"、")"需要先判断当前是否有数据存在,如果不存在数据,说明为false,有数据,应该检查括号是否匹配。
bool isValid(const string &s)
{
if (s.size() == 0)
return true;
//用vector模拟栈的方式进行括号匹配
vector<char> vec;
int index = 0;
for (int i = 0; i < s.size(); i++)
{
switch (s[i])
{
case '{':
case '(':
case '[':
vec.push_back(s[i]);
index++;
break;
case '}':
if (index == 0 || vec[index - 1] != '{')
{
return false;
}
index--;
vec.pop_back();
break;
case ')':
if (index == 0 || vec[index - 1] != '(')
{
return false;
}
index--;
vec.pop_back();
break;
case ']':
if (index == 0 || vec[index - 1] != '[')
{
return false;
}
index--;
vec.pop_back();
break;
default:
break;
}
} //end for
return vec.empty();
}
上述代码运行后,结果是两个都是100%,
可以看到上述代码中 “}”、"]"、")"这几种情况,有重复的代码,所以可以将代码进行抽取为一个函数,抽取后的代码为:
bool isMatch(char s1, char s2)
{
if (s1 == '(' && s2 == ')')
return true;
else if (s1 == '[' && s2 == ']')
return true;
else if (s1 == '{' && s2 == '}')
return true;
else
return false;
}
bool isValid(const string &s)
{
if (s.size() == 0)
return true;
//用栈的方式进行括号匹配
vector<char> vec;
int index = 0;
for (int i = 0; i < s.size(); i++)
{
switch (s[i])
{
case '{':
case '(':
case '[':
vec.push_back(s[i]);
index++;
break;
case '}':
case ']':
case ')':
if(vec.empty() || !isMatch(vec[index-1],s[i]))
{
return false;
}
index--;
vec.pop_back();
break;
default:
break;
}
} //end for
return vec.empty();
}
上述代码的运行时间为4ms,内存占用也多了,以下是详细情况: