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

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;,起到了記錄中間結果的作用,使得查詢不必每次都從頭開始,而且不會亂啊,是吧! 好開心,好緊張。開心我又做出來了一道題(而且是傳說中的模式匹配),緊張的是我要去做下一個嘍~~~