目录
二、(leetcode 1047)删除字符串中的所有相邻重复项
状态:已AC,列好所有情况就容易了
三种情况会出现不匹配的情况
- class Solution {
- public:
- bool isValid(string s) {
- if (s.size() % 2 != 0) return false;
- 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(']');
- else if(st.empty()||st.top()!=s[i])return false;
- else st.pop();
- }
- return st.empty();
- }
- };
状态:已AC
- class Solution {
- public:
- string removeDuplicates(string S) {
- stack<char> st;
- for(char t:S)
- {
- if(st.empty()||t!=st.top())
- {
- st.push(t);
- }
- else
- {
- st.pop();
- }
- }
- string result = "";
- while (!st.empty()) { // 将栈中元素放到result字符串汇总
- result += st.top();
- st.pop();
- }
- reverse(result.begin(),result.end());
- return result;
- }
- };
- class Solution {
- public:
- string removeDuplicates(string S) {
- string result;
- for(char s : S) {
- if(result.empty() || result.back() != s) {
- result.push_back(s);
- }
- else {
- result.pop_back();
- }
- }
- return result;
- }
- };
状态:已AC
思路:遇到数字则入栈;遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中
- class Solution {
- public:
- int evalRPN(vector
& tokens) { - stack<int> st;
- for (int i = 0; i < tokens.size(); i++) {
- if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
- int num1 = st.top();
- st.pop();
- int 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();
- st.pop(); // 把栈里最后一个元素弹出(其实不弹出也没事)
- return result;
- }
- };