Skip to content

Commit 7807651

Browse files
committed
392. Is Subsequence
1 parent 83920a7 commit 7807651

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
| 344 | Reverse String | [Ruby](./algorithms/ruby/0344-reverse-string.rb) | Easy |
4949
| 382 | Linked List Random Node | [Ruby](./algorithms/ruby/0382-linked-list-random-node.rb) | Medium |
5050
| 387 | First Unique Character in a String | [Ruby](./algorithms/ruby/0387-first-unique-character-in-a-string.rb) | Easy |
51+
| 392 | Is Subsequence | [Ruby](./algorithms/ruby/0392-is-subsequence.rb) | Easy |
5152
| 427 | Construct Quad Tree | [Ruby](./algorithms/ruby/0427-construct-quad-tree.rb) | Medium |
5253
| 438 | Find All Anagrams in a String | [Ruby](./algorithms/ruby/0438-find-all-anagrams-in-a-string.rb) | Medium |
5354
| 443 | String Compression | [Ruby](./algorithms/ruby/0443-string-compression.rb) [Python3](./algorithms/python3/0443-string-compression.py) | Medium |
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# frozen_string_literal: true
2+
3+
# 392. Is Subsequence
4+
# https://leetcode.com/problems/is-subsequence
5+
6+
=begin
7+
8+
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
9+
10+
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).
11+
12+
### Example 1:
13+
14+
Input: s = "abc", t = "ahbgdc"
15+
Output: true
16+
17+
### Example 2:
18+
19+
Input: s = "axc", t = "ahbgdc"
20+
Output: false
21+
22+
### Constraints:
23+
24+
* 0 <= s.length <= 100
25+
* 0 <= t.length <= 104
26+
* s and t consist only of lowercase English letters.
27+
28+
=end
29+
30+
# @param {String} s
31+
# @param {String} t
32+
# @return {Boolean}
33+
def is_subsequence(s, t)
34+
return true if s.size == 0
35+
return false if s.size > t.size
36+
37+
sp = 0
38+
t.chars.each do |char|
39+
if s[sp] == char
40+
sp += 1
41+
return true if sp == s.size
42+
end
43+
end
44+
45+
false
46+
end
47+
48+
# **************** #
49+
# TEST #
50+
# **************** #
51+
52+
require "test/unit"
53+
class Test_is_subsequence < Test::Unit::TestCase
54+
def test_
55+
assert_equal true, is_subsequence("abc", "ahbgdc")
56+
assert_equal false, is_subsequence("axc", "ahbgdc")
57+
end
58+
end

0 commit comments

Comments
 (0)