当前位置:网站首页>【力扣】判断子序列
【力扣】判断子序列
2022-08-11 05:31:00 【爱吃西瓜爱吃肉】
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
题目分析:即t字符串中(按顺序)包含s中的字符
方法一:双指针法
定义两个指针i,j,i指向字符串s,j指向t。while循环比较,指针j每次循环都加一,如果指向的字符相等,指针i加一 。如果i循环s结束即都找到了,返回true,也就是最后只需要比较i和s的长度
public static boolean isSubsequence(String s, String t) {
char[] tArray = t.toCharArray();
char[] sArray = s.toCharArray();
int i=0,j=0;
while(j< tArray.length && i < sArray.length){
if(sArray[i]==tArray[j]){
i++;
}
j++;
}
if(i== sArray.length) return true;
return false;
}
方法二:利用indexOf
indexOf,查找指定字符串,指定开始位置,返回该字符串出现的最早位置。如果没找到返回-1。循环s的字符数组,利用t字符串的indexOf方法找到当前的s字符。返回的下标作为下次循环的开始位置(题目:按顺序判断)。判断index如果等于-1即如果有一次没找到直接返回false
例如“axc”“acd”,中间x会找不到,index取值为0 -1。直接返回false,后面没必要继续找
public boolean isSubsequence(String s, String t) {
int index =-1;
if(s.equals("")) return true;
char[] sArray = s.toCharArray();
for(int i=0;i< sArray.length;i++){
index = t.indexOf(sArray[i],index+1);
if(index==-1)return false;
}
if(index!=-1) return true;
return false;
}
继续简化,当index=-1时直接返回Flase,如果已经出循环直接返回true,即全部找到了,不需要再判断了。不可能出现没找到的情况
public static boolean isSubsequence2(String s, String t) {
int index =-1;
char[] sArray = s.toCharArray();
for(int i=0;i< sArray.length;i++){
index = t.indexOf(sArray[i],index+1);
if(index==-1)return false;
}return true;
}
边栏推荐
- UE4打包工程失败问题记录
- C语言-6月8日-求两个数的最小公倍数和最大公因数;判断一个数是否为完数,且打印出它的因子
- 【剑指offer系列】面试题日记(前期题)
- Node stepping on the pit 80 port is occupied
- gerrit configure SSH Key and account, email information
- The role of the port
- 连接数据库时出现WARN: Establishing SSL connection without server‘s identity verification is not recommended.
- 第六届蓝帽杯 EscapeShellcode
- JS case exercise (classic case of teacher pink)
- helm安装
猜你喜欢
随机推荐
Day 81
Gradle 相关知识总结
无效的修订:3.18.1-g262b901-dirty
Byte (byte) and bit (bit)
Lua 快速入门(一)——基础语法
Jetpack use exception problem collection
PyQt5中调用.ui转换的.py文件代码解释
Jetpack's dataBinding
品优购项目实战笔记
USB URB
Day 83
lua-table引用传递和值传递
Unity3D中所有特殊的文件夹
unity小技巧
Node stepping on the pit 80 port is occupied
UML 中九种图
IndexError: index 9 is out of bounds for axis 0 with size 9;数组下标溢出问题
stack stack
[Meetup Preview] OpenMLDB+OneFlow: Link feature engineering to model training to accelerate machine learning model development
Compilation exception resolution