# 392. 判断子序列 [easy][貪心] 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 进阶: 如果有大量输入的 S,称作 S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码? 致谢: 特别感谢 @pbrother 添加此问题并且创建所有测试用例。 示例 1: ``` 输入:s = "abc", t = "ahbgdc" 输出:true ``` 示例 2: ``` 输入:s = "axc", t = "ahbgdc" 输出:false ``` 題解思路: 因為子字串是在原生字串不改變相對位置前提下,刪除一些字元形成的新字串。 s的每個字元,判斷t有沒有包含該字元。 如果有,取得該字元出現在t位置。 更新新的搜尋起始位置。index = index+1 重複對新的字元開始判斷。 ```java= class Solution { public boolean isSubsequence(String s, String t) { int index = -1; for(char c: s.toCharArray()){ index = t.indexOf(c, index+1); if(index == -1){ return false; } } return true; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up