Skip to content

Commit

Permalink
feat: Add isSubsequence string algorithm (#684)
Browse files Browse the repository at this point in the history
  • Loading branch information
sanjibgirics authored Oct 17, 2023
1 parent 25dea82 commit e255e17
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
35 changes: 35 additions & 0 deletions strings/issubsequence.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Checks if a given string is a subsequence of another string.
// A subsequence of a given string is a string that can be derived from the given
// string by deleting some or no characters without changing the order of the
// remaining characters. (i.e., "dpr" is a subsequence of "depqr" while "drp" is not).
// Author: sanjibgirics

package strings

// Returns true if s is subsequence of t, otherwise return false.
func IsSubsequence(s string, t string) bool {
if len(s) > len(t) {
return false
}

if s == t {
return true
}

if len(s) == 0 {
return true
}

sIndex := 0
for tIndex := 0; tIndex < len(t); tIndex++ {
if s[sIndex] == t[tIndex] {
sIndex++
}

if sIndex == len(s) {
return true
}
}

return false
}
75 changes: 75 additions & 0 deletions strings/issubsequence_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package strings_test

import (
"reflect"
"testing"

"github.com/TheAlgorithms/Go/strings"
)

func TestIsSubsequence(t *testing.T) {
var testCases = []struct {
name string
s string
t string
expected bool
}{
{
"Valid case 1 ",
"ace",
"abcde",
true,
},
{
"Invalid case 1",
"aec",
"abcde",
false,
},
{
"Empty strings",
"",
"",
true,
},
{
"s is more then t",
"aeccccc",
"abcde",
false,
},
{
"s is empty",
"",
"abcde",
true,
},
{
"Equal strings",
"aec",
"aec",
true,
},
{
"Valid case 2",
"pyr",
"wpxqyrz",
true,
},
{
"Invalid case 2",
"prx",
"wpxqyrz",
false,
},
}

for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
funcResult := strings.IsSubsequence(test.s, test.t)
if !reflect.DeepEqual(test.expected, funcResult) {
t.Errorf("expected: %v, got %v", test.expected, funcResult)
}
})
}
}

0 comments on commit e255e17

Please sign in to comment.