【Lintcode】1263. Is Subsequence

题目地址:

https://www.lintcode.com/problem/is-subsequence/description

给定两个字符串 s s s t t t,判断 s s s是否是 t t t的子序列。

用两个指针分别遍历 s s s t t t,先从 t t t中找 s [ 0 ] s[0] s[0],找到了之后再继续找 s [ 1 ] s[1] s[1],这样依次找下去。如果 s s s还没遍历完的时候, t t t已经遍历完了,说明不是,返回false,否则返回true。代码如下:

public class Solution {
    /**
     * @param s: the given string s
     * @param t: the given string t
     * @return: check if s is subsequence of t
     */
    public boolean isSubsequence(String s, String t) {
        // Write your code here
        int i = 0, j = 0;
        while (i < s.length() && j < t.length()) {
        	// 找s[i]
            while (j < t.length() && t.charAt(j) != s.charAt(i)) {
                j++;
            }
            // 遍历到末尾都没找到,返回false
            if (j == t.length()) {
                return false;
            }
            // 否则找到了,两个指针都向后移动
            i++;
            j++;
        }
        
        // 如果s没遍历完,说明s[i]没找到,返回false,否则返回true
        return i == s.length();
    }
}

时间复杂度 O ( n + m ) O(n+m) O(n+m),空间 O ( 1 ) O(1) O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值