392. Is Subsequence (使用 C 語言解題)

Easy
Topics
Companies

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

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

 

Constraints:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 104
  • s and t consist only of lowercase English letters.

 

Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?


google 翻譯:

給定兩個字串 s t,如果 s t 的子序列,則傳回 true,否則傳回 false

字串的子序列是在不影響剩餘字元相對位置的情況下刪除原始字串中的一些(可以是沒有)字元而形成的新字串。
(即“ace”“abcde”的子序列,而“aec”不是)。



想法一:

while 完整跑一次長字串,在跑的過程一併依序比較短字串是否依序在長字串中。
while 時只要判斷短字串是否已比較到結尾

寫法一:

bool isSubsequence(char* s, char* t) {
while(*s && *t) { // 完整跑一次
if(*s == *t) {// 比較短字串是否依序在長字串中
s++; // 下一次要比下個字元
if(!*s) // 提早結束
break;
}
t++;
}
return !*s;
}

結果一:
結果還可以,結案...



沒有留言:

張貼留言