Monday, September 5, 2016

Leetcode 392 : Is Subsequence

Problem Statement could be found at
https://leetcode.com/problems/is-subsequence/


Solution:- Since the original string is very big so DP is not suggested here. So the idea is to pick every character of pattern one by one and find in original string and keep a track of matching characters, if the match count equals final length then it is sub sequence otherwise not

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int index = 0;
        int i=0;
       
        int stringLength = t.size();
        int patternSize = s.size();
        int matchCount = 0;
        for (;(i<patternSize) && (index < stringLength );i++){
            char patternChar = s.at(i);
            while (index < stringLength){
               if (patternChar == t.at(index)){
                index++;  
                matchCount++;
                break;
               }
               index++;
            }
        }
        if ( matchCount == patternSize)
            return true;
        else
            return false;
    }
};