Problem
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
.
Solution
题意
给出两个字符串s和t,要求判断s是否是t的子串。
该题中对于子串的定义是:只要s中的字母以相同的顺序出现在t中,那么我们就说s是t的子串
示例见原题。
分析
从贪心算法的角度去看,解决这道题的思路是每判断一次都得到一个目前看起来最优的解,那么对于这道题来说,就要求每判断一次都能将问题的规模缩小。
所以解法就是。从s的第一个字母s[0]开始,从t[0]开始逐个匹配t中的字母,如果在t[i]处匹配,则继续匹配s[1],从t[i+1]开始。
重复这个过程,直到s中的字母全部完成匹配,则返回true
;否则,到达t[t.size()-1]时仍未完成s的匹配,返回false
。
Code
//Runtime: 68ms
class Solution {
public:
bool isSubsequence(string s, string t) {
int sIndex = 0, tIndex = 0; //index of string s and string t
int sSize = s.size(), tSize = t.size();
if (sSize == 0) return true; //if s is empty string, s is every string's sub-string
while (tIndex < tSize) { //check all characters of string t
if (s[sIndex] == t[tIndex]) {
sIndex++; //if s[sIndex] and t[tIndex] are matched, then check the next character of s
if (sIndex == sSize) //which means all characters of s are matched
return true;
}
tIndex++;
}
return false;
}
};