当前位置:网站首页>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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
猜你喜欢
随机推荐
shell 批量文件名(不含扩展名)小写改大写
MongoDB 遇见 spark(进行整合)
[learning notes] agc010
聊聊伪共享
[etc.] what are the security objectives and implementation methods that cloud computing security expansion requires to focus on?
高端了8年,雅迪如今怎么样?
Pay close attention to the work of safety production and make every effort to ensure the safety of people's lives and property
简单好用的代码规范
User management summary of mongodb
Realize the IP address home display function and number home query
Problems that cannot be accessed in MySQL LAN
Clion mingw64 Chinese garbled code
1. Deep copy 2. Call apply bind 3. For of in differences
MySQL error 28 and solution
【等保】云计算安全扩展要求关注的安全目标和实现方式区分原则有哪些?
Distributed transaction solution
JS function 返回多个值
记一次 .NET 某新能源系统 线程疯涨 分析
Cloud detection 2020: self attention generation countermeasure network for cloud detection in high-resolution remote sensing images
LIS 最长上升子序列问题(动态规划、贪心+二分)