当前位置:网站首页>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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
猜你喜欢

MongoDB内部的存储原理

单片机原理期末复习笔记
![[learning notes] zkw segment tree](/img/18/21f455a06e8629243fc5cf4df0044c.png)
[learning notes] zkw segment tree

Fast development board pinctrl and GPIO subsystem experiment for itop-imx6ull - modify the device tree file

How far can it go to adopt a cow by selling the concept to the market?

cmake 学习使用笔记(一)

Digital IC Design SPI

如何让join跑得更快?

Isprs2021/ remote sensing image cloud detection: a geographic information driven method and a new large-scale remote sensing cloud / snow detection data set

10 pictures open the door of CPU cache consistency
随机推荐
分布式事务解决方案
高端了8年,雅迪如今怎么样?
Use of polarscatter function in MATLAB
PCAP学习笔记二:pcap4j源码笔记
MongoDB命令汇总
作战图鉴:12大场景详述容器安全建设要求
Mongodb replication (replica set) summary
How to make the new window opened by electorn on the window taskbar
move base参数解析及经验总结
PAcP learning note 1: programming with pcap
MongoDB的用户管理总结
Clion mingw64 Chinese garbled code
如何让electorn打开的新窗口在window任务栏上面
Talk about pseudo sharing
Redis只能做缓存?太out了!
Fast development board pinctrl and GPIO subsystem experiment for itop-imx6ull - modify the device tree file
Why can basic data types call methods in JS
单片机学习笔记之点亮led 灯
Flink | 多流转换
Vscade editor esp32 header file wavy line does not jump completely solved