代码随想录算法训练营第11天 | 栈和队列

20.有效的括号

遇到左括号入栈,遇到右括号弹出

bool isValid(string s) {
	stack<char> kuohao;
	char c;
	for (char a : s) {
		switch (a)
		{
			case'(':
			case'{':
			case'[':
				kuohao.push(a);
				break;
			case')':
			case'}':
			case']':
				if (kuohao.empty())
					return false;
				c = kuohao.top();
				kuohao.pop();
				if ((a == ')' && c == '(') || (a == ']' && c == '[') || (a == '}' && c == '{'))
					continue;
				else
					return false;
		default:
			break;
		}
	}
	if (kuohao.empty())
		return true;
	return false;
}

1047.删除字符串中的所有相邻重复项

  • 使用栈
string removeDuplicates(string s) {
	
	stack<char> st;
	for (int i = 0; i < s.size(); i++) {
		if (st.empty()||st.push(s[i]);)
		{
			st.push(s[i]);
			continue;
		}
		else if (s[i] == st.top())
			st.pop();
	}

	string result="";    
	int size = st.size();

	for (int j = 0; j < size; j++) {
		result+= st.top();   //字符串string可以+=,不能result[j]=
		st.pop();
	}

	reverse(result.begin(), result.end());
	return result;
}
  • 直接使用字符串string,不用再翻转转换
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;
    }

150.逆波兰表达式求值

关于string和int间的相互转换

int evalRPN(vector<string>& tokens) {

	stack<int> number;

	for (string s : tokens) {
		if (s == "*" || s == "+" || s == "/" || s == "-")
		{
			int a, b;
			a = number.top();
			number.pop();
			b = number.top();
			number.pop();
			if (s == "*")  number.push(a * b);
			else if (s == "/")  number.push(b / a);
			else if (s == "+")  number.push(a + b);
			else if (s == "-")  number.push(b - a);
		}
		else
			number.push(stoi(s));
	}
	return number.top();
}

关于返回局部变量

posted @   daydayup_cpp  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示