392. Is Subsequence

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 sand 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?

M1: two pointers

在t的长度范围内,比较两个指针指向的字母是否相同。如果相同,移动s指针,如果s到末尾了,返回true,无论是否相同,每次循环都移动t指针。如果t也走到末尾了,返回false

time: O(n), space: O(1)

class Solution {
    public boolean isSubsequence(String s, String t) {
        if(s.length() == 0) {
            return true;
        }
        int i = 0, j = 0;
        while(j < t.length()) {
            if(s.charAt(i) == t.charAt(j)) {
                i++;
                if(i == s.length()) {
                    return true;
                }
            }
            j++;
        }
        return false;
    }
}

M2: follow-up: binary search

需要对大量的s来check t,preprocess t 并存下信息比较合理。可以用hashmap存,遍历t并把每个字母作为key存入hashmap,value是字母出现的索引(list)。然后遍历s,对于s中的每个字母,先取出map中对应的下标list,再用binary search查找 是否存在大于当前字母前一个字母的下标(prev)的 当前字母的出现位置,如果不存在直接返回false,如果存在,prev自增1,直到遍历完s

time: O(MKlogN)  -- M: average length of s, K: number of s, N: length of t (assuming all chars in t are the same)

space: O(length of t)

class Solution {
    public boolean isSubsequence(String s, String t) {
        Map<Character, List<Integer>> map = new HashMap<>();
        for(int i = 0; i < t.length(); i++) {
            map.putIfAbsent(t.charAt(i), new ArrayList<>());
            map.get(t.charAt(i)).add(i);
        }
        
        int prev = -1;
        for(int i = 0; i < s.length(); i++) {
            List<Integer> list = map.get(s.charAt(i));
            if(list == null) {
                return false;
            } else {
                prev = binarySearch(list, prev);
                if(prev == -1) {
                    return false;
                }
                prev++;
            }
        }
        return true;
    }
    
    public int binarySearch(List<Integer> list, int target) {
        int left = 0, right = list.size() - 1;
        while(left <= right) {
            int mid = left + (right - left) / 2;
            if(list.get(mid) < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left == list.size() ? -1 : list.get(left);
    }
}
原文地址:https://www.cnblogs.com/fatttcat/p/10245867.html