GoLang Function of Checking Is Subsequence

in #golang3 years ago
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

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

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false

Is Subsequence Algorithm in GoLang


Two Pointers, moving both pointers i and j if the s[i] is equal to t[j]. Otherwise, only move pointer j until j reaches the end.

func isSubsequence(s string, t string) bool {
    var ls, lt = len(s), len(t)
    if ls > lt {
        return false
    }
    var i, j = 0, 0
    for i < ls && j < lt {
        if s[i] == t[j] {
            i += 1
        }
        j += 1
    }
    return i == ls
}

Assuming length of s is smaller than t - the time complexity is O(N) where N is the number of strings in t. The space complexity is O(1).

Subsequence Algorithms in Other Programming Languages:

Hey, in Python, you can do this in Pythonic way: Python Function to Check Subsequence

--EOF (The Ultimate Computing & Technology Blog) --

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

  1. Voting Algorithm Updated to Favor those High Delegations!
  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

how are you @justyy good day
The work you do is greatly appreciated, thanks to that we can do ours without inconvenience. I hope that more people value the work of the witness
have a great day

Hello brother Justyy I have delegated to you as much as 600 SP, my first post after my delegation got a vote of 6.69%, my second post did not get a vote from you missed, my third post got 6.65% votes, the next post arrived currently i only get 1.46%.

Please explain, Brother Justyy?

thank you

Coin Marketplace

STEEM 0.17
TRX 0.15
JST 0.028
BTC 59986.17
ETH 2417.93
USDT 1.00
SBD 2.45