题1
链接:20. 有效的括号
繁琐版实现(本人写
class Solution {
public:
bool isValid(string s) {
//定义栈
stack<char> st;
for(int i = 0;i < s.size();i++){
//遇到左括号压入
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
if(s[i] == '(')st.push(')');
if(s[i] == '{')st.push('}');
if(s[i] == '[')st.push(']');
}
//遇到右括号比对
else if(s[i] == ')' || s[i] == ']' || s[i] == '}'){
if(st.empty())return false;
if(st.top() == s[i]){
st.pop();
}
else{
return false;
}
}
}
if(!st.empty())return false;
return true;
}
};
参考:
class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') st.push(')');
else if (s[i] == '{') st.push('}');
else if (s[i] == '[') st.push(']');
// 第三种情况:遍历字符串匹配的过程中,栈已经为空了,没有匹配的字符了,说明右括号没有找到对应的左括号 return false
// 第二种情况:遍历字符串匹配的过程中,发现栈里没有我们要匹配的字符。所以return false
else if (st.empty() || st.top() != s[i]) return false;
else st.pop(); // st.top() 与 s[i]相等,栈弹出元素
}
// 第一种情况:此时我们已经遍历完了字符串,但是栈不为空,说明有相应的左括号没有右括号来匹配,所以return false,否则就return true
return st.empty();
}
};
题2
没能排错的代码:
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(int i = s.size();i >= 0;i--){
if(!st.empty()){
if(st.top() == s[i]){
st.pop();
}
else{
st.push(s[i]);
}
}
else if(st.empty())st.push(s[i]);
}
//赋值
for(int i = 0;i < st.size();i++){
s[i] = st.top();
st.pop();
}
s.erase(st.size() + 1);
return s;
}
};
提交通过
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(int i = s.size() - 1;i >= 0;i--){
if(!st.empty()){
if(st.top() == s[i]){
st.pop();
}
else{
st.push(s[i]);
}
}
else if(st.empty())st.push(s[i]);
}
//赋值
string result = "";
while(!st.empty()){
result += st.top();
st.pop();
}
return result;
}
};
题3
第一次解(未考虑最开始输入的都是数字的情况)
class Solution {
public:
int evalRPN(vector<string>& tokens) {
//定义一个栈
stack<long long> st;
long long result = stoll(tokens[0]);
for(int i = 1;i < tokens.size();i++){
if(tokens[i] == "+"){
result = result + st.top();
}else if(tokens[i] == "-"){
result -= st.top();
}else if(tokens[i] == "*"){
result *= st.top();
}else if(tokens[i] == "/"){
result /= st.top();
}
else{
st.push(stoll(tokens[i]));
}
}
return result;
}
};
知识点:
1. stoll(tokens[i])其中stoll是C++标准库中的一个函数,用于将字符串转换成长整型。
2. long long result = stoll(tokens[0]);转换成长整型之后用long long接收
看完答案后的解:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
long long res = stoll(tokens[0]);
for(int i = 0;i < tokens.size();i++){
if(tokens[i] == "+"||tokens[i] == "-"||tokens[i] == "*"||tokens[i] == "/"){
long long nums1 = st.top();
st.pop();
long long nums2 = st.top();
st.pop();
if(tokens[i] == "+"){
res = nums1 + nums2;
}else if(tokens[i] == "-"){
res = nums2 - nums1;
}else if(tokens[i] == "*"){
res = nums2 * nums1;
}else if(tokens[i] == "/"){
res = nums2 / nums1;
}
st.push(res);
}else{
st.push(stoll(tokens[i]));
}
}
return res;
}
};