题目:392. Is Subsequence
- Total Accepted: 28646
- Total Submissions: 64661
- Difficulty: Medium
- Contributor: LeetCode
Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace"
is a subsequence of "abcde"
while "aec"
is not).
Example 1:
s = "abc"
, t = "ahbgdc"
Return true
.
Example 2:
s = "axc"
, t = "ahbgdc"
Return false
.
Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
解题思路:
s1,s2分别为s和t的长度,s的第一位在t中的位置的范围为0~s2-s1,s的第二位在t中的位置的范围为第一位的位置+1~s2-s1+1。s中的每一位的位置范围都可以按照这个规则递推下去。对于s中的每一位,在t中这个范围中搜索,若找到则继续搜索下一位,若没找到则直接返回false。直到每一位都找到了则返回true。
代码:
class Solution {
public:
bool isSubsequence(string s, string t) {
bool check = false;
int s1 = s.size();
int s2 = t.size();
if(s1 == 0)
return true;
else if(s2 == 0)
return false;
int begin = 0;
int end = s2 - s1;
for(int i = 0; i < s1; i++){
check = false;
for(int j = begin; j < end + 1; j++){
if(s[i] == t[j]){
check = true;
begin = j + 1;
end ++;
break;
}
}
if(!check)
return false;
}
return check;
}
};
做完之后看了solution里面的代码发现同样的思路能够用更简洁的代码来实现,我的代码有一点复杂了。参考代码(java)如下:
public class Solution {
public boolean isSubsequence(String s, String t) {
if (s.length() == 0) return true;
int indexS = 0, indexT = 0;
while (indexT < t.length()) {
if (t.charAt(indexT) == s.charAt(indexS)) {
indexS++;
if (indexS == s.length()) return true;
}
indexT++;
}
return false;
}
}