392. Is Subsequence

为何不像76. Minimum Window Substring用数组来匹配, 是因为双指针是根据字符串的顺序遍历的, 而数组的话没有顺序.如

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC". 并不是非得ABC的顺序. 看follow up 是如何用list[] 和binary search解决字符配的升序问题的

https://leetcode.com/problems/is-subsequence/#/solutions

http://www.cnblogs.com/EdwardLiu/p/6116896.html

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?

Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.

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

  

Follow Up:

The best solution is to create a map for String t, key is char, value is the index of appearance in ascending order

public boolean isSubsequence(String s, String t) {
        List<Integer>[] idx = new List[256]; // Just for clarity  字典集合, 每一个字母的ASCII 码当作键, 在t中的顺序当作值
        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;  // 前一个字母在t中的坐标, 控制升序
        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;            //在升序后找不到false
            prev = idx[s.charAt(i)].get(j) + 1;                        //在t中查找当前s的字母比s中的前一个字母在t中升序的坐标
    } 
    return true;
}

  

posted @ 2017-07-01 11:24  apanda009  阅读(376)  评论(0编辑  收藏  举报