Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

There are 3 possible approaches: DP, divide&conquer and greedy. And apparently, DP has O(n^2) complexity (TLE), DivideConquer can only be worse. Greedy can be O(n)! And its code is amazingly brief:

class Solution {
public:
    bool isSubsequence(string s, string t) {
        size_t lens = s.length();
        size_t lent = t.length();

        int is = 0, it = 0;
        while(is < lens && it < lent)
        {
            char cs = s[is], ct = t[it];
            if(cs != ct) it ++;
            else is++, it++;
        }
        
        return is == lens;
    }
};
posted on 2016-10-24 03:25  Tonix  阅读(96)  评论(0)    收藏  举报