当前位置:网站首页>双指针模拟
双指针模拟
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;
}
}边栏推荐
- What is the future development trend of Business Intelligence BI
- MySQL 因字符集问题插入中文数据时提示代码 :1366
- Deep learning and neural networks: the six most noteworthy trends
- 2022春招面试总结
- Picture tools
- Detailed explanation of Base64 coding and its variants (to solve the problem that the plus sign changes into a space in the URL)
- 单目双视三维坐标确定
- 关于ETL看这篇文章就够了,三分钟让你明白什么是ETL
- 不能改变虚拟机电源状态报错解决方案
- 第七章 操作位和位串(三)
猜你喜欢
随机推荐
利用sonar做代码检查
Earthly container image construction tool -- the road to dream
打印出来的对象是[object object],解决方法
JS merge multiple objects and remove duplicates
Why do you want to file? What are the advantages and disadvantages of website filing?
Several schemes of PHP code encryption
Smart power plant: how to make use of easycvr to build a safe, stable, green and environment-friendly intelligent inspection platform
Ordering of MySQL composite index
Centos7 installation of jdk8, mysql5.7 and Navicat connection to virtual machine MySQL and solutions (solutions to MySQL download errors are attached)
There was an error checking the latest version of pip
【力扣10天SQL入门】Day3
Detailed explanation of Base64 coding and its variants (to solve the problem that the plus sign changes into a space in the URL)
[explain the difference between operation and maintenance and network engineering]
利用ngrok做内网穿透
Vscode install the remote -wsl plug-in to connect to the local WSL
api平台通用签名机制
小程序云数据,数据请求一个集合数据的方法
Shell pass parameters
Redis cluster data skew
pymysql 向MySQL 插入数据无故报错









