392. Is Subsequence

140 阅读1分钟

Given two strings s and t, return true if s is a subsequence of t , or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

 

Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false

答案

go

func isSubsequence(s string, t string) bool {
	sn := len(s)
	tn := len(t)
	si := 0
	ti := 0

	for si < sn && ti < tn {
		if s[si] == t[ti]{
			si++
			ti++
		}else {
			ti++
		}
	}
	
	return si == sn
}

c++

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int sn = s.size();
        int tn = t.size();
        
        int si = 0;
        int ti = 0;
        
        while (si < sn && ti < tn) {
            if (s[si] == t[ti]){
                si++;
                ti++;
            }else{
                ti++;
            }
        }
        return si == sn;
    }
};