[Leetcode 392]判断子序列 Is Subsequence

时间:2023-03-09 00:30:16
[Leetcode 392]判断子序列 Is Subsequence

【思路】

判断s是否为t的子串,所以length(s)<=length(t)。于是两个指针,一次循环。

将s、t转换为数组p1、p2。

i为过程中s的匹配长度。

i=0空串,单独讨论返回true。

当i=p1.length-1时返回true,否则循环结束返回false。

【代码】

class Solution {
public boolean isSubsequence(String s, String t) {
char []p1=s.toCharArray();
char []p2=t.toCharArray();
if(p1.length==0){
return true;
}
int i=0;
for(int j=0;j<p2.length;j++){
if(p2[j]==p1[i]){
if(i==p1.length-1){
return true;
}
i++;
}
}
return false;
}
}

【举例】