leetcode之392. Is Subsequence(C++解法 動態規劃 貪心 模式匹配)

題目:
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.

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?

*****************************我是一條分割線*******************

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int coun=s.size();
        int posi=-1;
        int i=0;
        char* str = new char[2];
        str[1] = '\0';
        while(i<coun)
        {
            str[0] = s[i];
            size_t pos=t.find_first_of(str,posi+1,1);
            if(pos==string::npos)
            {
                return false;
            }
            posi=pos;
            i++;
        }
        return true;
    }
};

這個是在對上一道題好好消化之後自己完成的哦,而且一次提交AC(accept),開心三秒鐘。
下面開始劃重點:
1、string上的find操作有很多,這道題目用到的三個參數的意思是(假定三個參數從左到右分別是a,b,c)從字符串t的第b個位置以c爲單位逐個匹配*字符串**a,所以第一個參數是字符串類型哦,開始時想破頭皮不知道怎麼把s[i]當做字符串傳進去,在請教了大神之後,char str = new char[2]橫空出世(雖然我到現在這個地方還是有點點不太清楚,不過很好的幫我解決了問題)。
2、動態規劃的思想上一篇已經總結過了,那這道題上的最優子結構該怎麼描述呢?(我試一下)在t串中尋找s串中的第i個字母,找到之後,從找到的位置後面接着尋找s串中的第(i+1)個字母,如果沒有找到的話,就證明t串後面的字母中都不存在你要找的s[i]了,終止返回false即可。所以這個地方我認爲用到了動態規劃的地方就是posi=pos;,起到了記錄中間結果的作用,使得查找不必每次都從頭開始,而且不會亂啊,是吧! 好開心,好緊張。開心我又做出來了一道題(而且是傳說中的模式匹配),緊張的是我要去做下一個嘍~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章