day11
20. 有效的括号
题目链接/文章讲解/视频讲解:programmercarl.com/0020.%E6%9C…
思路: 利用栈先进后出的原则,当匹配到右括号时,去栈顶寻找是否括号匹配。
代码:
class Solution {
public:
bool isValid(string s) {
int index = 0;
int size = s.size();
stack<char> sstack;
while(size--){
printf("%c ",s[index]);
if((s[index] != ')'&&s[index]!=']')&&s[index]!='}')
{
sstack.push(s[index]);
}else{
if(sstack.empty()) {
return false;
}
char tmp = s[index];
char top = sstack.top();
if(tmp == ')' && top != '(') {
return false;
}
if(tmp == ']' && top !='[') {
return false;
}
if(tmp == '}' && top !='{') {
return false;
}
sstack.pop();
}
index++;
}
if(sstack.empty()) return true;
else
{
return false;
}
}
};
1047. 删除字符串中的所有相邻重复项
栈的经典应用。
要知道栈为什么适合做这种类似于爱消除的操作,因为栈帮助我们记录了 遍历数组当前元素时候,前一个元素是什么。
题目链接/文章讲解/视频讲解:programmercarl.com/1047.%E5%88…
思路: 本题较为简单,主要是利用栈来保存之前的元素,保证当出栈时,前面的元素可以保存下来。
代码:
class Solution {
public:
string removeDuplicates(string s) {
int size = s.size();
stack<char> sstack;
int index = 0;
while(size--){
if(!sstack.empty())
{
char top = sstack.top();
if(top == s[index]) sstack.pop();
else sstack.push(s[index]);
}else sstack.push(s[index]);
index++;
}
string str;
int ssize = sstack.size();
while(ssize--){
char top = sstack.top();
sstack.pop();
str+=top;
}
reverse(str.begin(),str.end());
return str;
}
};
150. 逆波兰表达式求值
本题不难,但第一次做的话,会很难想到,所以先看视频,了解思路再去做题
题目链接/文章讲解/视频讲解:programmercarl.com/0150.%E9%80…
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
long long num1 = st.top();
st.pop();
long long num2 = st.top();
st.pop();
if (tokens[i] == "+") st.push(num2 + num1);
if (tokens[i] == "-") st.push(num2 - num1);
if (tokens[i] == "*") st.push(num2 * num1);
if (tokens[i] == "/") st.push(num2 / num1);
} else {
st.push(stoll(tokens[i]));
}
}
int result = st.top(); //直接return 了long long 一直报错
st.pop(); // 把栈里最后一个元素弹出(其实不弹出也没事)
return result;
}
};