392. Is Subsequence

本文介绍了一个用于检查一个字符串是否为另一个字符串子序列的有效算法。通过迭代比对的方式,该算法能够在较短的时间内完成判断,适用于处理大量字符串的场景。

题目:392. Is Subsequence


  • Total Accepted: 28646 
  • Total Submissions: 64661 
  • Difficulty: Medium
  • Contributor: LeetCode

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?


解题思路:

s1,s2分别为s和t的长度,s的第一位在t中的位置的范围为0~s2-s1,s的第二位在t中的位置的范围为第一位的位置+1~s2-s1+1。s中的每一位的位置范围都可以按照这个规则递推下去。对于s中的每一位,在t中这个范围中搜索,若找到则继续搜索下一位,若没找到则直接返回false。直到每一位都找到了则返回true。


代码:

class Solution {
public:
    bool isSubsequence(string s, string t) {
    	bool check = false;
        int s1 = s.size();
        int s2 = t.size();
        if(s1 == 0)
        	return true;
        else if(s2 == 0)
        	return false;
        int begin = 0;
        int end = s2 - s1;
        for(int i = 0; i < s1; i++){
        	check = false;
        	for(int j = begin; j < end + 1; j++){
        		if(s[i] == t[j]){
        			check = true;
        			begin = j + 1;
        			end ++;
        			break;
        		}
        	}
        	if(!check)
        		return false;
        }
        return check;
    }
};

做完之后看了solution里面的代码发现同样的思路能够用更简洁的代码来实现,我的代码有一点复杂了。参考代码(java)如下:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值