LeetCode #392: Is Subsequence

weixin_33806914發表於2017-04-30

Problem

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 t. t 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.

Solution

題意

給出兩個字串s和t,要求判斷s是否是t的子串。

該題中對於子串的定義是:只要s中的字母以相同的順序出現在t中,那麼我們就說s是t的子串

示例見原題。

分析

從貪心演算法的角度去看,解決這道題的思路是每判斷一次都得到一個目前看起來最優的解,那麼對於這道題來說,就要求每判斷一次都能將問題的規模縮小。

所以解法就是。從s的第一個字母s[0]開始,從t[0]開始逐個匹配t中的字母,如果在t[i]處匹配,則繼續匹配s[1],從t[i+1]開始。

重複這個過程,直到s中的字母全部完成匹配,則返回true;否則,到達t[t.size()-1]時仍未完成s的匹配,返回false

Code

//Runtime: 68ms
class Solution {
public:
    bool isSubsequence(string s, string t) {
        int sIndex = 0, tIndex = 0;             //index of string s and string t
        int sSize = s.size(), tSize = t.size();
        if (sSize == 0) return true;         //if s is empty string, s is every string's sub-string
        while (tIndex < tSize) {                //check all characters of string t
            if (s[sIndex] == t[tIndex]) {
                sIndex++;                       //if s[sIndex] and t[tIndex] are matched, then check the next character of s
                if (sIndex == sSize)            //which means all characters of s are matched
                    return true;
            }
            tIndex++;
        }
        return false;
    }
};

相關文章