LeetCode 392. Is Subsequence (判断子序列)

题目标签:Greedy

  设两个 pointers,s_index  和  t_index;

  如果 s_index  和  t_index 位置上的字母一样,那么继续移动两个 pointers;

  如果字母不一样,只移动 t_index;

  具体看code。

 

Java Solution:

Runtime:  7 ms, faster than 80.12% 

Memory Usage: 44.5 MB, less than 100.00%

完成日期:02/19/2020

关键点:two pointers

class Solution {
    public boolean isSubsequence(String s, String t) {
        if(s.length() == 0) 
            return true;
        
        int s_index =0, t_index = 0;
        
        // use two pointers to find char in s and t
        while(t_index < t.length()) {
            if(s.charAt(s_index) == t.charAt(t_index)) { // if found the match, move s_index to next one
                s_index++;
                if(s_index == s.length())
                    return true;
            }
            t_index++;
        }
        return false;
    }
}

参考资料:LeetCode Discuss

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2020-02-20 09:56  Jimmy_Cheng  阅读(147)  评论(0编辑  收藏  举报