给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"
是"abcde"
的一个子序列,而"aec"
不是)。
示例 1:
s = "abc"
, t = "ahbgdc"
返回 true
.
示例 2:
s = "axc"
, t = "ahbgdc"
返回 false
.
双指针
思路:字符串s和字符串t逐个字符进行匹配,up在t上进行移动,down在s上进行移动。当down到达s的结尾时,说明匹配成功。
时间复杂度:O(sLen+tLen),其中 sLen 为 s 的长度,tLen 为 tt的长度。每次无论是匹配成功还是失败,都有至少一个指针发生右移,两指针能够位移的总距离为 sLen+tLen。
class Solution {
public boolean isSubsequence(String s, String t) {
if(s == null || s.equals("")){
return true;
}
char[] chars = s.toCharArray();
char[] chart = t.toCharArray();
int sLen = s.length();
int tLen = t.length();
int up=0, down=0;
while(up < tLen && down < sLen){
if(chart[up] == chars[down]){
up++;
down++;
}else{
up++;
}
}
return down == sLen;
}
}