当前位置:网站首页>2022-7-7 Leetcode 844. Compare strings with backspace
2022-7-7 Leetcode 844. Compare strings with backspace
2022-07-07 13:39:00 【weixin_ fifty-one million one hundred and eighty-seven thousand】
Method 1 : Stack
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;
}
};
Method 2 : Double pointer
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;
}
};
author :demigodliu
link :https://leetcode.cn/problems/backspace-string-compare/solution/shuang-zhi-zhen-bi-jiao-han-tui-ge-de-zi-8fn8/
source : Power button (LeetCode)
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .
边栏推荐
猜你喜欢
SSRF漏洞file伪协议之[网鼎杯 2018]Fakebook1
记一次 .NET 某新能源系统 线程疯涨 分析
Xshell connection server changes key login to password login
Error lnk2019: unresolved external symbol
[Presto profile series] timeline use
118. 杨辉三角
High end for 8 years, how is Yadi now?
2022-7-6 Leetcode27.移除元素——太久没有做题了,为双指针如此狼狈的一天
"New red flag Cup" desktop application creativity competition 2022
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
随机推荐
Talk about pseudo sharing
toRaw和markRaw
ESP32系列专栏
118. Yanghui triangle
Introduce six open source protocols in detail (instructions for programmers)
JS function returns multiple values
LIS longest ascending subsequence problem (dynamic programming, greed + dichotomy)
Mongodb command summary
云计算安全扩展要求关注的安全目标和实现方式区分原则有哪些?
PHP - laravel cache
[daily training] 648 Word replacement
JS slow motion animation principle teaching (super detail)
C语言数组相关问题深度理解
118. 杨辉三角
高端了8年,雅迪如今怎么样?
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
交付效率提升52倍,运营效率提升10倍,看《金融云原生技术实践案例汇编》(附下载)
一文读懂数仓中的pg_stat
Getting started with cinnamon applet
ESP32构解工程添加组件