给定字符串 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.
解题思路:
动态规划:dp[i]表示字符串s中的第i个字符在字符串t中出现。
此题的关键思想是查找s中的第i个字符的前提是第i-1个字符已经在s中找到,即dp[i-1]==1
代码实现:
class Solution {
public boolean isSubsequence(String s, String t) {
int sLen=s.length();
int tLen=t.length();
int[] dp=new int[sLen];
if(sLen<=0){
return true;
}
int i=0,j=0;
while(i<sLen&&j<tLen){
if(s.charAt(i)==t.charAt(j)){
dp[i]=1;
i++;
j++;
continue;
}
j++;
}
if(i==sLen&&dp[i-1]==1){
return true;
}
if(i<sLen-1||dp[i]==0)
return false;
return true;
}
}