力扣-1544题 整理字符串(C++)

该博客主要讨论了如何解决 LeetCode 上的一个问题——`makeGood` 函数实现。给定一个字符串,需要移除相邻且大小写不同的字符以优化字符串。作者提供了两种解决方案,一种使用栈数据结构,另一种通过遍历并比较相邻字符实现。这两种方法都有效地解决了问题,展示了对字符串操作和算法的理解。
摘要由CSDN通过智能技术生成

题目链接:https://leetcode-cn.com/problems/make-the-string-great/
题目如下:
在这里插入图片描述
在这里插入图片描述

class Solution {
public:
    string makeGood(string s) {
	stack<char> stk;
	string result = "";

	for (int i = 0; i<s.length(); i++) {
		if (!stk.empty()) {
			char ch1 = stk.top();
			char ch2 = s[i];

			if (abs(ch1 - ch2) == 32) stk.pop();
			else stk.push(s[i]);
		}
		else {
			stk.push(s[i]);
		}
	}

	for (int i = 0; i<stk.size();/*i++*/) {//最开始没去除i++,拼接结果不符合要求
		result=stk.top()+result;
		//cout << result<< endl;
		stk.pop();
	}

	return result;
}
};

// class Solution{
// public:
// string makeGood(string s) {
//     string res="";
//     for (int i=0;i<s.size()-1;) {
//         if ((s[i] >= 'a' && s[i] <= 'z') && (s[i+1] >= 'A' && s[i+1] <= 'Z')) {
//             i+=2;
//         }
//         else if ((s[i] >= 'A' && s[i] <= 'Z') && (s[i+1] >= 'a' && s[i+1] <= 'z')) {
//             i+=2;
//         }
//         else {
//             res += s[i];
//             ++i;
//         }  

//     }
//     return res;
// }
// };
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值