My code:
public class Solution {
public boolean isSubsequence(String s, String t) {
if (s == null || t == null) {
return false;
}
else if (t.length() < s.length()) {
return false;
}
int pre = 0;
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
int index = t.indexOf("" + curr, pre);
if (index == -1) {
return false;
}
pre = index + 1;
}
return true;
}
}
reference:
https://discuss.leetcode.com/topic/57205/java-only-2ms-much-faster-than-normal-2-pointers
public class Solution {
public boolean isSubsequence(String s, String t) {
if (s == null || t == null) {
return false;
}
else if (t.length() < s.length()) {
return false;
}
else if (s.length() == 0) {
return true;
}
int j = 0;
char target = s.charAt(0);
for (int i = 0; i < t.length(); i++) {
char curr = t.charAt(i);
if (curr == target) {
j++;
if (j >= s.length()) {
return true;
}
target = s.charAt(j);
}
}
return false;
}
}
reference:
https://discuss.leetcode.com/topic/57241/simple-java-code-with-explanation
public class Solution {
public boolean isSubsequence(String s, String t) {
if (s == null || t == null) {
return false;
}
else if (t.length() < s.length()) {
return false;
}
else if (s.length() == 0) {
return true;
}
List<Integer>[] idx = new List[256];
for (int i = 0; i < t.length(); i++) {
char curr = t.charAt(i);
if (idx[curr] == null) {
idx[curr] = new ArrayList<Integer>();
}
idx[curr].add(i);
}
int pre = 0;
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (idx[curr] == null) {
return false;
}
List<Integer> list = idx[curr];
int index = Collections.binarySearch(list, pre);
if (index < 0) {
index = -index - 1;
}
if (index >= list.size()) {
return false;
}
pre = list.get(index) + 1;
}
return true;
}
}
reference:
https://discuss.leetcode.com/topic/58367/binary-search-solution-for-follow-up-with-detailed-comments
用三種不同的做法都寫了下磺陡。其實(shí)都是 greedy思想的延伸。
前兩個做法很相似。就是根據(jù)在t中找到s對應(yīng)character 的index罩句,然后一步步縮小搜索范圍辟拷。
第三種做法其實(shí)也是這個原理帐姻,只不過用了binary search 來實(shí)現(xiàn)沃缘。每次搜索的時間是 O(log M), M = size of that sub list
可以說易阳,接近于常數(shù)級操作蔚舀。
介紹下 饵沧,Collections.binarySearch 這個函數(shù)。
如果傳入的list包含target赌躺,那就返回他的index
如果不包含狼牺,返回一個數(shù), index which is < 0
我們做如下轉(zhuǎn)換:
index = -index - 1;
就可以得到這個target如果插入list礼患,應(yīng)該插入的index
所以一開始pre = 0是钥,如果0 這個index不在對應(yīng)的list里面,那么就會返回 -1 => 轉(zhuǎn)換得到0,
就代表缅叠,s中的這個character悄泥,應(yīng)該對應(yīng)于t中的index這個位置。
就是上面解法的 pre
然后一步步縮小范圍肤粱。
其實(shí)也是 Greedy 思想的延伸弹囚。
Anyway, Good luck, Richardo! -- 09/20/2016