November 30, 2023

Viiisit [LeetCode] - 392. Is Subsequence

#php#javascript#ruby

keep learning, keep coding!

Problem - Is Subsequence

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).

翻譯蒟蒻

給定兩個字串 s 和 t,如果 s 是 t 的子序列,則返回 true;否則返回 false。例如,”ace” 是 “abcde” 的子序列,而”aec”則不是。換句話說,如果字串 s 的所有字都按照相對順序出現在字串 t 中,即使其中有些字被刪除,仍然視為 s 是 t 的子序列。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isSubsequence = function(s, t) {
let i = 0;
let j = 0;

while (i < s.length && j < t.length) {
if (s[i] === t[j]) {
// 如果 s 中的字與 t 中的字相等,將 i 往後移動
i++;
}
// 不管是否相等,j 都要往後移動
j++;
}

// 如果 i 走到底,代表 s 中的字都在 t 中出現過
return i === s.length;
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
def is_subsequence(s, t)
i = 0
j = 0

while i < s.length && j < t.length
if s[i] == t[j]
i += 1
end
j += 1
end

i == s.length
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
function isSubsequence($s, $t) {
$sLen = strlen($s);
$tLen = strlen($t);
$i = 0;
$j = 0;
while ($i < $sLen && $j < $tLen) {
if ($s[$i] == $t[$j]) {
$i++;
}
$j++;
}
return $i == $sLen;
}

LeetCode 傳送門 - Is Subsequence