当前位置:网站首页>双指针模拟
双指针模拟
2022-06-24 07:07:00 【厚积薄发ض】
使用双指针法分别对两个字符串进行遍历操作
- 定义skip来记录#,以此来进行抵消
- 定义两个指针,从后往前开始遍历
- 在遍历时两指针会出现三种情况
1.第一次遇到# --->记录#
2.skip的个数不为0 -->进行抵消
3.第一次遇到非#-->跳出循环开始比较
- 最后进行两字符串之间字符的比较
class Solution {
public boolean backspaceCompare(String s, String t) {
int skipS =0;//记录s字符串中的#号数量
int skipT =0;//记录t字符串中的#号数量
//两指针从后往前遍历字符串
int i =s.length()-1;//指向s-->遍历字符串s
int j =t.length()-1;//指向t-->遍历字符串t
while(i>=0||j>=0){//两个字符串都遍历完才结束,跳出循环证明是相等的字符串
//对字符串s进行处理
//1.第一次遇到# --->记录#
//2.skip的个数不为0 -->进行抵消
//3.第一次遇到非#-->跳出循环开始比较
while(i>=0){
if(s.charAt(i)=='#') {
skipS++;
i--;
}else if(skipS>0) {
skipS--;
i--;
}else {
break;
}
}
//同样对j也做同样的处理
while(j>=0){
if(t.charAt(j)=='#'){
skipT++;
j--;
}else if(skipT>0){
skipT--;
j--;
}else {
break;
}
}
//此时字符串都进行了相应的处理接下来开始比较两字符串
if(i>=0&&j>=0){
if(s.charAt(i)!=t.charAt(j)){
//两字符不相等
return false;
}
}else {
if((i>=0&&j<0)||(j>=0&&i<0)){
//证明有一个字符串已经越界
return false;
}
}
//继续遍历字符串
i--;
j--;
}
return true;
}
}边栏推荐
- JS to get the last element of the array
- 【量化投资】离散傅里叶变换求数组周期
- “不平凡的代理初始值设定不受支持”,出现的原因及解决方法
- 【NOI模拟赛】摆(线性代数,杜教筛)
- Introduction to data platform
- 關於ETL看這篇文章就够了,三分鐘讓你明白什麼是ETL
- 一文详解|增长那些事儿
- 提高INSERT速度
- 1844. 将所有数字用字符替换
- Easycvr invokes the interface parameter acquisition method and precautions of device video recording on the page
猜你喜欢

js中通过key查找和更新对象中指定值的方法

分布式 | 如何与 DBLE 进行“秘密通话”

【NOI模拟赛】给国与时光鸡(构造)

【团队管理】测试团队绩效管理的25点小建议

Xiaohei ai4code code baseline nibble 1

MATLAB Camera Calibrator相机标定

2022.06.23(LC_144,94,145_二叉树的前序、中序、后序遍历)

liunx服务器 telnet 带用户名 端口登陆方法

It is enough to read this article about ETL. Three minutes will let you understand what ETL is

日本大阪大学万伟伟研究员介绍基于WRS系统机器人的快速集成方法和应用
随机推荐
liunx服务器 telnet 带用户名 端口登陆方法
Glusterfs replacement failure brick
Use cpulimit to free up your CPU
“不平凡的代理初始值设定不受支持”,出现的原因及解决方法
lombok 使用
定时备份数据库脚本
[team management] 25 tips for testing team performance management
数据中台:中台架构及概述
Shell basic operator -- arithmetic operator
更改SSH端口号
Shell basic operators -- relational operators
Blue screen error UNMOUNTABLE boot volume of the solution
相机投影矩阵计算
Picture tools
Video Fusion communication has become an inevitable trend of emergency command communication. How to realize it based on easyrtc?
Shell array
uniapp 热更新后台管理
关于ETL看这篇文章就够了,三分钟让你明白什么是ETL
Qt 中发送自定义事件
Increase insert speed