392 Is Subsequence

178 篇文章 0 订阅
160 篇文章 0 订阅

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

2 尝试解

2.1 分析

判断字符串t只通过删除操作能否变为字符串s,即s是否为t的子串。

只需两个指针,index_s和index_t,index_t一直向后移动,如果找到了s[index_x],则两者都向后移动一位。如果任意指针到达结尾,则结束程序。判断index_s==s.size()。

如果有多个s,这个方法会比较费时。可以用map<char,vector>记录每个字母出现的所有次序,判断s是否为子串时,变量LastOrder记录上一个配对的字符出现的位置,初始为-1,然后依次找下一个字母出现的次序列表中,是否有比LastOrder更大的次序,如果有,LastOrder取其中的最小次序,然后判断s中的下一个字符,否则返回false。而且由于vector中是按顺序添加的,可以用二分法查找大于LastOrder的最小次序。

2.2 代码

方法一:双遍历

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int s_index = 0;
        int t_index = 0;
        while(s_index < s.size() && t_index < t.size()){
            while(t_index < t.size() && t[t_index] != s[s_index])
                t_index++;
            if(t_index < t.size()){
                s_index++;     
                t_index++;
            }

        }
        return s_index == s.size();
    }
};

 方法二:HashMap 单遍历

class Solution {
public:
    bool isSubsequence(string s, string t) {
        vector<vector<int>> letter_order(26);
        for(int i = 0; i < t.size();i++){
            letter_order[t[i]-'a'].push_back(i);
        }
        int last_order = -1;
        for(int i = 0; i < s.size(); i++){
            if(!letter_order[s[i]-'a'].size() || letter_order[s[i]-'a'].back() <= last_order )
                return false;
            for(auto order : letter_order[s[i]-'a']){
                if(order > last_order){
                    last_order = order;
                    break;
                }
            }
        }
        return true;
    }
};

3 标准解

bool isSubsequence(string s, string t) {
    int sLen = s.length(), sIdx = 0, tLen = t.length();
    for (int i=0; i<tLen && sIdx<sLen; i++) 
        if (t[i]==s[sIdx]) sIdx++;
    return sIdx==sLen;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值