当前位置:网站首页>2022-7-7 Leetcode 844.比较含退格的字符串
2022-7-7 Leetcode 844.比较含退格的字符串
2022-07-07 11:36:00 【weixin_51187533】
方法一:栈
class Solution {
public:
bool backspaceCompare(string s, string t) {
string tmps = "", tmpt = "";
for (auto& ch:s){
if (ch == '#'){
if (!tmps.empty())
tmps.pop_back();
}else tmps.push_back(ch);
}
for (auto& ch:t){
if (ch == '#'){
if (!tmpt.empty())
tmpt.pop_back();
}else tmpt.push_back(ch);
}
return tmps == tmpt;
}
};
方法二:双指针
class Solution {
public:
bool backspaceCompare(string S, string T) {
int i = S.length() - 1, j = T.length() - 1;
int skipS = 0, skipT = 0;
while (i >= 0 || j >= 0) {
while (i >= 0) {
if (S[i] == '#') {
skipS++, i--;
} else if (skipS > 0) {
skipS--, i--;
} else {
break;
}
}
while (j >= 0) {
if (T[j] == '#') {
skipT++, j--;
} else if (skipT > 0) {
skipT--, j--;
} else {
break;
}
}
if (i >= 0 && j >= 0) {
if (S[i] != T[j]) {
return false;
}
} else {
if (i >= 0 || j >= 0) {
return false;
}
}
i--, j--;
}
return true;
}
};
作者:demigodliu
链接:https://leetcode.cn/problems/backspace-string-compare/solution/shuang-zhi-zhen-bi-jiao-han-tui-ge-de-zi-8fn8/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- Introduction and basic use of stored procedures
- 信号强度(RSSI)知识整理
- Navicat运行sql文件导入数据不全或导入失败
- [QNX Hypervisor 2.2用户手册]6.3.4 虚拟寄存器(guest_shm.h)
- Summary of import, export, backup and recovery of mongodb
- Flink | 多流转换
- How did Guotai Junan Securities open an account? Is it safe to open an account?
- Realize the IP address home display function and number home query
- 单片机原理期末复习笔记
- 1、深拷贝 2、call apply bind 3、for of for in 区别
猜你喜欢
随机推荐
Clion mingw64 Chinese garbled code
How did Guotai Junan Securities open an account? Is it safe to open an account?
How far can it go to adopt a cow by selling the concept to the market?
Getting started with cinnamon applet
MongoDB 分片总结
MongoDB的导入导出、备份恢复总结
[learning notes] segment tree selection
OSI 七层模型
How to make join run faster?
shell 批量文件名(不含扩展名)小写改大写
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
DID登陆-MetaMask
工具箱之 IKVM.NET 项目新进展
Mongodb meets spark (for integration)
单片机原理期末复习笔记
【等保】云计算安全扩展要求关注的安全目标和实现方式区分原则有哪些?
Server to server (S2S) event (adjust)
将数学公式在el-table里面展示出来
MongoDB优化的几点原则
648. 单词替换 : 字典树的经典运用