算法作業_32(2017.6.15第十七週)

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.

分析:看到題目,很容易想到最長公共子序列問題,所以用動態規劃求解,但是提交時報內存溢出:Memory Limit Exceeded

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int n = s.size();
        int m  = t.size();
        vector<vector<int>>dp (n+1,vector<int>(m+1));
        
        for(int i = 0 ; i <= n ; i ++){
            
            for(int j = 0 ; j <= m; j ++){
                if(i == 0  || j == 0 ){
                    dp[i][j] = 0 ;
                }else if(s[i-1] == t[j-1]){
                    dp[i][j] = dp[i-1][j-1] + 1;
                }else {
                    dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
                }
            }
        }
        
        if(dp[n][m] == n ){
            return true ;
        }else{
            return false;
        }
    }
};

解法二:簡單考慮,直接用兩個for循環去遍歷即可:

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int n = s.size();
        int m = t.size();
        int pos = 0;
        
        for(int i = 0 ; i < n ; i ++){
        bool flag = false;
            for(int j = pos ; j<m; j++){
                if(s[i] == t[j]){
                    pos = j+1;
                    flag = true;
                    break;
                    }
                }
                if(flag == false)
                    return false;
            }
            return true;
        }
    };


發佈了59 篇原創文章 · 獲贊 2 · 訪問量 9097
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章