LeetCode //C - 392. Is Subsequence

2023-12-20 09:03:47

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

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 <= 10^4
  • s and t consist only of lowercase English letters.

From: LeetCode
Link: 392. Is Subsequence


Solution:

Ideas:
  • We use two index variables, sIndex and tIndex, to traverse the strings s and t, respectively.
  • We iterate through t using tIndex, and for each character in t, we check if it matches the current character of s pointed to by sIndex.
  • If there is a match, we move to the next character in s.
  • We keep iterating until we reach the end of either string.
  • If we reach the end of s (i.e., s[sIndex] == ‘\0’), it means all characters of s were found in t in the correct order, and we return true.
  • Otherwise, if we reach the end of t first, it means s is not a subsequence of t, and we return false.
Code:
bool isSubsequence(char* s, char* t) {
    int sIndex = 0; // Index for string s
    int tIndex = 0; // Index for string t

    // Iterate through both strings
    while (s[sIndex] != '\0' && t[tIndex] != '\0') {
        if (s[sIndex] == t[tIndex]) {
            // Move to next character in s if there's a match
            sIndex++;
        }
        // Always move to next character in t
        tIndex++;
    }

    // If we've reached the end of s, then it's a subsequence of t
    return s[sIndex] == '\0';
}

文章来源:https://blog.csdn.net/navicheung/article/details/135098646
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。