当前位置:网站首页>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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
猜你喜欢
cmake 学习使用笔记(一)
作战图鉴:12大场景详述容器安全建设要求
线程池拒绝策略最佳实践
迅为iTOP-IMX6ULL开发板Pinctrl和GPIO子系统实验-修改设备树文件
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
Talk about pseudo sharing
About how appium closes apps (resolved)
Digital IC Design SPI
我那“不好惹”的00后下属:不差钱,怼领导,抵制加班
室内ROS机器人导航调试记录(膨胀半径的选取经验)
随机推荐
Custom thread pool rejection policy
Write it down once Net a new energy system thread surge analysis
Use of polarscatter function in MATLAB
单片机学习笔记之点亮led 灯
Show the mathematical formula in El table
作战图鉴:12大场景详述容器安全建设要求
ESP32系列专栏
High end for 8 years, how is Yadi now?
分屏bug 小记
RecyclerView的数据刷新
Problems that cannot be accessed in MySQL LAN
Why can basic data types call methods in JS
Shell batch file name (excluding extension) lowercase to uppercase
Milkdown 控件图标
MongoDB复制(副本集)总结
Cmake learning and use notes (1)
[learning notes] agc010
室内ROS机器人导航调试记录(膨胀半径的选取经验)
My "troublesome" subordinates after 00: not bad for money, against leaders, and resist overtime
User management summary of mongodb