20. 有效的括号
初见想法:无
class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0) return false;
unordered_map<char, char> dic;
dic[')'] = '(';
dic['}'] = '{';
dic[']'] = '[';
stack<char> queue;
for (int i = 0; i < s.size(); i++)
{
if (dic.find(s[i]) == dic.end())
{
queue.push(s[i]);
}
else
{
if (queue.empty()) return false;
char t = queue.top();
queue.pop();
if (t != dic[s[i]]) return false;
}
}
if (!queue.empty()) return false;
return true;
}
};
靠自己想出来的方法写出来的,虽然只击败了 1.99%
以下方法为官方答案:
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> dic;
dic.insert({{'(', ')'}, {'[', ']'}, {'{', '}'}, {'?', '?'}});
stack<char> st;
st.push('?');
for (int i = 0; i < s.size(); i++)
{
if (dic.find(s[i]) != dic.end())
{
st.push(s[i]);
}
else
{
char temp = st.top();
st.pop();
if (dic[temp] != s[i]) return false;
}
}
if (st.size() == 1) return true;
else return false;
}
};
注意unordered_map的插入方法
官方答案中,多了一个映射,stack里的数据数量至少为1,不用判断为空
1047. 删除字符串中的所有相邻重复项
stack能够了解传入数据的前一项是什么,这个是关键重点,自己写的
class Solution {
public:
string removeDuplicates(string s) {
string ans;
if (s.empty()) return ans;
stack<char> st;
for (int i = 0; i < s.size(); i++)
{
if (!st.empty() && s[i] == st.top()) st.pop();
else st.push(s[i]);
}
while (!st.empty())
{
char temp = st.top();
st.pop();
ans.push_back(temp);
}
reverse(ans.begin(), ans.end());
return ans;
}
};
官方答案:
class Solution {
public:
string removeDuplicates(string s) {
string stk;
for (char ch : s) {
if (!stk.empty() && stk.back() == ch) {
stk.pop_back();
} else {
stk.push_back(ch);
}
}
return stk;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/solutions/643955/shan-chu-zi-fu-chuan-zhong-de-suo-you-xi-4ohr/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
注意string有push_back(), pop_back(), back(), 这些函数
150. 逆波兰表达式求值
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
int ans = 0;
for (int i = 0; i < tokens.size(); i++)
{
if (tokens[i] == "+")
{
int x = st.top();
st.pop();
int y = st.top();
st.pop();
st.push(x + y);
}
else if (tokens[i] == "-")
{
int x = st.top();
st.pop();
int y = st.top();
st.pop();
st.push(y - x);
}
else if (tokens[i] == "*")
{
int x = st.top();
st.pop();
int y = st.top();
st.pop();
st.push(x * y);
}
else if (tokens[i] == "/")
{
int x = st.top();
st.pop();
int y = st.top();
st.pop();
st.push(y / x);
}
else
{
st.push(atoi(tokens[i].c_str()));
}
}
return st.top();
}
};
官方答案更加简洁,注意string/char字符串转int的手法,atoi(const char* c), string.c_str()用来把string转为char类型字符串