LeetCode #392 Is Subsequence 是否為子序列

英文原文如下

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

中文翻譯

給予兩個字串 st,如果 st 的子序列,則返回 true,否則返回 false。

字串的子序列是透過刪除原始字串中的某些字符(可以為零個)而不干擾其餘字符的相對位置而形成的新字串。換句話說,”ace” 是 “abcde” 的子序列,而 “aec” 則不是。

範例及題目限制


解題思路

而要解決這一題其實也不複雜,只需要用到一個迴圈以及一個int變數

C# 解決方案

方案1

public class Solution {
    public bool IsSubsequence(string s, string t) {
        if(s=="")
            return true;
        char[] arr = s.ToCharArray();
        int idx = 0;

        for(int i = 0; i< t.Length;i++)
        {
            if(t[i]==arr[idx])
            {
                idx+=1;
                if(idx==arr.Length)
                {
                    return true;
                }
            }
        }
        return false;
    }
}

在我們的解決方案中,我們對 t 的每一個字符迭代,並隨時與s中指定index位置的值比較

若出現符合的,則index位置 +1,就會在下一次迭代中對 s 的下一個位置比較

而當變數 idx 與 s 的長度相等時,就代表全部查完了,該字串 s 為子序列!

Java解決方案

方案1

class Solution {
    public boolean isSubsequence(String s, String t) {
        if(s.equals(""))
            return true;
        char[] arr = s.toCharArray();
        int idx = 0;

        for(int i = 0; i< t.length();i++)
        {
            if(t.charAt(i)==arr[idx])
            {
                idx+=1;
                if(idx==arr.length)
                {
                    return true;
                }
            }
        }
        return false;
    }
}

Python3 解決方案

方案1

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        if s=="":
            return True
        idx = 0

        for i in range(len(t)):
            if(t[i]==s[idx]):
                idx = idx+1
                if(idx==len(s)):
                    return True
        return False    

JavaScript 解決方案

方案1

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
var isSubsequence = function(s, t) {
    if(s=="")
        return true;
    var idx = 0;

    for(let i = 0; i< t.length;i++)
    {
        if(t[i]==s[idx])
        {
            idx+=1;
            if(idx==s.length)
            {
                return true;
            }
        }
    }
    return false;
};

結論

相當簡單的一題,唯一要想的可能就是最前面的規劃上

不然 for 迴圈、ToCharArray() 以及變數作為索引 應該都是基礎的技能了

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Is Subsequence – LeetCode

其他的LeetCode文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *