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中的字母以相同的順序出現(xiàn)在t中令蛉,那么我們就說s是t的子串
示例見原題。
分析
從貪心算法的角度去看式镐,解決這道題的思路是每判斷一次都得到一個目前看起來最優(yōu)的解,那么對于這道題來說,就要求每判斷一次都能將問題的規(guī)睦绸茫縮小周蹭。
所以解法就是趋艘。從s的第一個字母s[0]開始,從t[0]開始逐個匹配t中的字母凶朗,如果在t[i]處匹配瓷胧,則繼續(xù)匹配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;
}
};