2019年11月1日 星期五

Is Subsequence


Is Subsequence

  • Lintcode : 1263 / Leetcode : 392
  • Level : Easy

Problem

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 (length <= 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
Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:

Input: s = `"axc"`, t = `"ahbgdc"`
Output: false
Challenge
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?

Concept & Algorithm

1. 計算每一個字元出現的次數,儲存在unordered_map<char, int> count
2. 宣告int length 儲存長度 
3. 宣告bool hasOdd 紀錄是否有出現奇數的字元
3. iterate count,假設遍歷到的字元是偶數個 length 就直接加總
4. 若是奇數個就加上該數目減去1,且將hasOdd變成true
5. 最後假設hasOdd為false,直接return length / 若為true,return length + 1

Time Complexity & Space Complexity

time : O(n)
space: O(1)

Answer

class Solution {
public:
    /**
     * @param s: the given string s
     * @param t: the given string t
     * @return: check if s is subsequence of t
     */
    bool isSubsequence(string &s, string &t) {
        if (s.size() == 0) return true;
        if (t.size() == 0) return false;
        int indS = 0, indT = 0;
        int sizeS = s.size(), sizeT = t.size();
        while (indS < sizeS && indT < sizeT) {
            if (s[indS] == t[indT]) {
                indS++;
            }
            indT++;
        }
        if (indS < sizeS) return false;
        return true;
    }
};
tags: 2pointers

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...