给定字符串s
和t
,判断s
是否为t
的子序列。
你可以认为在s
和t
中都只包含小写字母。t
可能是一个非常长(length ~= 500,000
)的字符串,而s
是一个较短的字符串(length <= 100
)。
一个字符串的子序列是在原字符串中删去一些字符(也可以不删除)后,不改变剩余字符的相对位置形成的新字符串(例如,"ace"
是"abcde"
的子序列而"aec"
不是)。
样例
样例1:
s = "abc"
,t = "ahbgdc"
返回true
。
样例2:
s = "axc"
,t = "ahbgdc"
返回false
。
挑战
如果输入包含很多S
串,例如为S1, S2, ..., Sk
,其中k >= 1B
,你想一个一个判断T
是否包含这样的子序列。在这样的情形下,你会怎样修改你的代码呢?
解题思路:
遍历一遍t,如果两指针指向的值相等,则同时加加,继续考察下一组元素,否则只加tt,最后若ss指向末尾了,说明true,否则为false。
public class Solution {
/**
* @param s: the given string s
* @param t: the given string t
* @return: check if s is subsequence of t
*/
public boolean isSubsequence(String s, String t) {
// Write your code here
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
int i=0, j=0;
while(i < ss.length && j < tt.length){
if(ss[i] == tt[j]){
i++;
j++;
}else{
j++;
}
}
if(i == ss.length)
return true;
return false;
}
}