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

Solution1:Two pointers

思路:
Time Complexity: O(s.len + t.len) Space Complexity: O(1)

Solution2:Binary Search

For follow up: 如果t很長的話 且 很對不同s多次調(diào)用,可以使用這種方法先建立buildTPosMap,會快。
Time Complexity: O(s.len * log(t.len)) Space Complexity: O(1)
思路: 對t建立一個hashmap,是每個字符 -> 該字符所有位置組成list 的map。拿到s后,遍歷s的每個字符,在map對應(yīng)字符的位置list中,二分查找得到最近的可用位置,最近可用意味著是在前一個字符得到的位置之后(變量prev)的最近位置。(list一定是遞增的,所以可以利用二分查找)

屏幕快照 2017-09-08 上午12.05.01.png

Solution1 Code:

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

Solution2 Code:

class Solution2 {
    private List<Integer>[] t_pos_map = new List[256];
    
    public boolean isSubsequence(String s, String t) {
        buildTPosMap(t);
        
        int prev = 0;
        for (int i = 0; i < s.length(); i++) {
            if (t_pos_map[s.charAt(i)] == null) return false; 
            int j = Collections.binarySearch(t_pos_map[s.charAt(i)], prev);
            if (j < 0) j = -j - 1;
            if (j == t_pos_map[s.charAt(i)].size()) return false;
            prev = t_pos_map[s.charAt(i)].get(j) + 1;
        }
        return true;
    }
    
    private void buildTPosMap(String t) {
        for (int i = 0; i < t.length(); i++) {
            if (t_pos_map[t.charAt(i)] == null)
                t_pos_map[t.charAt(i)] = new ArrayList<>();
            t_pos_map[t.charAt(i)].add(i);
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容