Leetcode 392. Is Subsequence

Leetcode 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.

题目大意:
给定两个字符串s和t,判断s是不是t的子序列,其中t很长(~=5000),s较短(<=100)。

解题思路1:
利用贪心思想,设置两个指针i和j指向两个字符串,比较s[i]和t[j],如果相等则同时后移,如果不等则j后移。若i指向s的终结符,则说明匹配成功,返回true,反之返回false。注意空字符串s也是t的子序列。时间复杂度为O(m+n),其中m,n分别为s和t的长度。

代码:

class Solution {
public:
    bool isSubsequence(string s, string t) {
        if(s.length() > t.length())
            return false;
        if(s.empty())
            return true;
        int i = 0, j = 0;
        while(j < t.size())
        {
            if(s[i] == t[j])
            {
                i++;
                j++;
            }
            else
                j++;
            if(i == s.size())
                return true;
        }
        return false;
    }
};

解题思路2:
可以结合哈希表和二分查找的方法,遍历t将其中的字母存放到“字母-位置”的键值对中,由于字母会重复出现储存位置的数据结构是一个vector。此时,每一个位置vector中的元素都是有序的,可以采取二分查找的方法。遍历s,在哈希表中查找键s[i],若不存在直接返回false,若存在,判断其位置是否大于上一个s元素的匹配位置,因此需要设置一个位置指针pre用于每次匹配后的更新。时间复杂度为O(n+mlogn),其中m,n分别为s和t的长度。

代码:

class Solution {
public:
    bool isSubsequence(string s, string t) {
        if(s.empty())
            return true;
        unordered_map<int, vector<int>> m;
        int pre = -1, lent = t.size(), lens = s.size();
        for(int i = 0; i < lent; i++)
            m[t[i] - 'a'].push_back(i);
        for(int i = 0; i < lens; i++)
        {
            auto it = upper_bound(m[s[i] - 'a'].begin(), m[s[i] - 'a'].end(), pre);
            if(it == m[s[i] - 'a'].end())
                return false;
            pre = *it;
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值