题目要求
Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not).
Example 1:
s = "abc", t = "ahbgdc"
Return true.
Example 2:
s = "axc", t = "ahbgdc"
Return false.
Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
如何判断字符串s是否是字符串t的一个子序列。子序列是指s中的字母均按照相对位置存在于t中,比如"abc"是"ahbfdc"的一个子序列,但是"axc"就不是"ahbgdc"的一个子序列。
思路一:java API
java中提供了一个String.indexOf(char c, int startIndex)
的方法,这个方法是指从字符串中的startIndex位置开始往后找,返回第一个c所在的下标,如果找不到,则返回-1。利用这个方法我们可以快速的解决这个问题。
public boolean isSubsequence(String s, String t) {
if(s==null || s.length()==0) return true;
int start = -1;
for(int i = 0 ; i
思路二:二分法
二分法的思路主要是指,首先我们遍历字符串t,找到每个字符在t中出现的位置。当我们知道每个字符在t中出现的所有下标后,就开始遍历s,并开始找到距离上一个字符所在的位置之后的当前字符的最小下标。
举例:
s="abc"
t="acbgbc"
遍历t之后可以得到这样一个字段:
a:{0}
b:{2,4}
g:{3}
c:{1,5}
之后遍历s,并用一个index来记录当前字符所在的下标,index初始时为-1。
s[0] = a, a:{0} -> index = 0
s[1] = b, b:{2,4} -> index = 2
s[2] = c, c:{1,5} -> index=5
可以看到我们能够找到一个合法的序列,使得当前字母的起始下标始终大于上一个字母的下标。
public boolean isSubsequence(String s, String t) {
List[] idx = new List[256]; // Just for clarity
for (int i = 0; i < t.length(); i++) {
if (idx[t.charAt(i)] == null)
idx[t.charAt(i)] = new ArrayList<>();
idx[t.charAt(i)].add(i);
}
int prev = 0;
for (int i = 0; i < s.length(); i++) {
if (idx[s.charAt(i)] == null) return false; // Note: char of S does NOT exist in T causing NPE
int j = Collections.binarySearch(idx[s.charAt(i)], prev);
if (j < 0) j = -j - 1;
if (j == idx[s.charAt(i)].size()) return false;
prev = idx[s.charAt(i)].get(j) + 1;
}
return true;
}
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~