LeetCode/solutions/392. Is Subsequence.md
2019-12-24 13:13:19 +08:00

1.7 KiB
Raw Blame History

392. Is Subsequence

思路

题目要求判断字符串s是否是字符串t的子序列。

思路一

这题是个easy题基本思想确实很简单我们可以用两个指针p1和p2分别作用于s和t。然后不断右移指针进行匹配。

时间复杂度O(n)空间复杂度O(1)

思路二

题目还问如果有源源不断的s进来且每次t都是保持不变的那么函数该如何优化。为了能快速定位某个字符在t中的位置我们可以考虑有hash 由于同一个字符可能在t中出现了多次所以这个hash是字符到数组的映射。 对于s中的每个字符s[i]假设s[i-1]对应t中匹配位置是pre那么我们查找s[i]在t中出现的位置中第一个大于pre的位置这可用二分查找upper_bound.

C++

思路一

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int p1 = 0, p2 = 0;
        // if(s.size() > t.size()) return false;
        while(p1 < s.size() && p2 < t.size()){
            while(p2 < t.size() && t[p2] != s[p1]) p2++;
            p1++; p2++;
        }
        return (p1 == s.size() && p2 <= t.size());
    }
};

思路二

class Solution {
public:
    bool isSubsequence(string s, string t) {
        unordered_map<char, vector<int>>mp;
        for(int i = 0; i < t.size(); i++) 
            mp[t[i]].push_back(i);
        
        int pre = -1;
        for(char &c: s){
            auto it = upper_bound(mp[c].begin(), mp[c].end(), pre);
            if(it == mp[c].end()) return false; // 查找失败
            pre = *it; // 更新pre
        }
        return true;
    }
};