刷题笔记
//20 自己写的ac了,但是写的不好,可以参考卡哥的。点这里
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] == '['){
st.push(s[i]);
}
else{
if(st.empty()) return false;
if(s[i] == ')'){
if(st.top() == '(') st.pop();
else return false;
}
if(s[i] == '}'){
if(st.top() == '{') st.pop();
else return false;
}
if(s[i] == ']'){
if(st.top() == '[') st.pop();
else return false;
}
}
}
if(st.empty()) return true;
else return false;
}
};
//1047
//自己ac了 , 跟卡哥差不多
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
string result;
for(int i = 0; i < s.size(); i++){
if(st.empty()) st.push(s[i]);
else{
if(st.top() == s[i]){
st.pop();
}
else st.push(s[i]);
}
}
while(!st.empty()){
result += st.top(); //给字符串添加字符
st.pop();
}
reverse(result.begin(),result.end()); //reverse是原地反转,无返回值,参数是指针
return result;
}
};
//150
//挺简单的,但是要注意很多细节!!!
//longlong不能改成int,会溢出,因为给的不一定是个int的数
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st; //栈里存的long long类型
for(int i = 0; i < tokens.size(); i++){
if(tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/"){
st.push(stoll(tokens[i]));//stoll函数!!!
}
else{
long long a = st.top();
st.pop();
long long b = st.top();
st.pop();
if(tokens[i] == "+") st.push(b + a);//“”双引号不能写成单引号。和python不一样
else if(tokens[i] == "-") st.push(b - a);//注意是b-a
else if(tokens[i] == "*") st.push(b * a);
else st.push(b / a);
}
}
return st.top();
}
};
重点
stoll函数:此函数将在函数调用中作为参数提供的字符串转换为long long int。它解析str并将其内容解释为指定基数的整数,并将其作为long long int类型的值返回。
(s to longlong这么记)