Part1:问题描述
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 sis 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?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
Part2:解题思路
这一题我用的暴力解题,直接2个for循环判断s里的字符有没有在t中出现,值得注意的是字符出现的顺序也要一致。我觉得我有改进的地方在于第二个for循环的时候我用的下标是一个函数里面的全局变量index,这样就可以保证下一次从t中开始找的字符是上一次判断用过的字符之后的。第一个if里面有嵌套的一个if是因为不加类似第一个样例--最后一个相等的字符在最后出现时的样例判断会出错。
Part3:代码
class Solution {
public:
bool isSubsequence(string s, string t) {
int length1 = s.length();
int length2 = t.length();
if (length1 > length2) return false;
int index = 0;
int i = 0;
for (i; i < length1; i++) {
for (index; index < length2; ) {
if (s[i] == t[index++]) {
if (index == length2 && i != length1 - 1) {
return false;
}
break;
}
if (index == length2) {
return false;
}
}
}
return true;
}
};
本文介绍了一个经典的字符串匹配问题——检查一个字符串是否为另一个字符串的子序列,并提供了一种使用双循环进行暴力匹配的方法。该方法适用于短字符串s与长字符串t的匹配场景。
323

被折叠的 条评论
为什么被折叠?



