392. Is Subsequence 判斷子序列

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?

給定字符串s和t,判斷s是否是t的子序列。
這里假定s和t都只含有小寫字母,t可以是非常長的字符串(長度約為500,000),s是短字符串(長度小于100)。
注意子序列是由原生序列中的某些元素按照相對位置不變的狀態(tài)組成的新序列。
進(jìn)階:若輸入的待檢測短序列s有很多個(gè),而你又想一個(gè)一個(gè)檢測是否為t的子序列,如何改寫你的代碼?


思路
簡單的做法,t中依次對s的首個(gè)字母進(jìn)行匹配,成功則匹配s的下一個(gè)字母,直到s被匹配完成(返回true)或t掃描結(jié)束且s仍未匹配完(返回false),這里注意,對于s為空的情況,總是匹配為true。

class Solution {
public:
    bool isSubsequence(string s, string t) {
        if(s.size()>t.size()) return false;
        if(s=="")   return true;
        for(auto sit=s.begin(),tit=t.begin(); tit!=t.end();tit++){
            if(*sit==*tit)  sit++;
            if(sit==s.end())    return true;
        }
        return false;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,121評論 0 23
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,922評論 0 33
  • 《請停止無效努力》讀書筆記:第七章 回歸真實(shí)的自己:善用情緒,才能掌控人生 第二篇 如何應(yīng)對自己的功利心——上進(jìn)是...
    木小悠閱讀 218評論 0 0
  • 我難過,卻不能說;我不說,心里就更難過。雖然朋友圈里并沒有幾個(gè)人可說話,可是也無法在朋友圈里說。我喜歡這個(gè)陌生的地...
    煙羽_閱讀 312評論 0 0
  • 今天午餐和師姐一起吃,真不好意思,第一次聚餐還是師姐請的。我們倆太窮了,交了一筆保險(xiǎn)費(fèi),就捉襟見肘了,僅剩一個(gè)月的...
    張洛伊閱讀 281評論 0 0

友情鏈接更多精彩內(nèi)容