1. 程式人生 > >【LeetCode】392 判斷子序列 (C++)

【LeetCode】392 判斷子序列 (C++)

題目描述:

給定字串 s 和 t ,判斷 s 是否為 t 的子序列。

你可以認為 s 和 t 中僅包含英文小寫字母。字串 t 可能會很長(長度 ~= 500,000),而 s 是個短字串(長度 <=100)。

字串的一個子序列是原始字串刪除一些(也可以不刪除)字元而不改變剩餘字元相對位置形成的新字串。(例如,"ace"是"abcde"的一個子序列,而"aec"不是)。

示例 1:
s = "abc", t = "ahbgdc"

返回 true.

示例 2:
s = "axc", t = "ahbgdc"

返回 false.

解題方案:

查詢子序列,因為字串t很長,所以如果按照傳統的判斷方法時間複雜度不好,由於是有序的,所以從在主串查詢到第一個字元的下一個位置開始查詢。

程式碼:

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int len = s.length();
        if(len == 0)
            return true;
        int i = 0;
        int pos = t.find(s[i], pos);
        while(i < len)
        {
            
            if(pos != string :: npos)
                i ++;
            else
                break;
            pos = t.find(s[i], pos + 1);
        }
        if(i == len)
            return true;
        else 
            return false;
    }
};