Leetcode 392. Is Subsequence
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.
题目大意:
给定两个字符串s和t,判断s是不是t的子序列,其中t很长(~=5000),s较短(<=100)。
解题思路1:
利用贪心思想,设置两个指针i和j指向两个字符串,比较s[i]和t[j],如果相等则同时后移,如果不等则j后移。若i指向s的终结符,则说明匹配成功,返回true,反之返回false。注意空字符串s也是t的子序列。时间复杂度为O(m+n),其中m,n分别为s和t的长度。
代码:
class Solution {
public:
bool isSubsequence(string s, string t) {
if(s.length() > t.length())
return false;
if(s.empty())
return true;
int i = 0, j = 0;
while(j < t.size())
{
if(s[i] == t[j])
{
i++;
j++;
}
else
j++;
if(i == s.size())
return true;
}
return false;
}
};
解题思路2:
可以结合哈希表和二分查找的方法,遍历t将其中的字母存放到“字母-位置”的键值对中,由于字母会重复出现储存位置的数据结构是一个vector。此时,每一个位置vector中的元素都是有序的,可以采取二分查找的方法。遍历s,在哈希表中查找键s[i],若不存在直接返回false,若存在,判断其位置是否大于上一个s元素的匹配位置,因此需要设置一个位置指针pre用于每次匹配后的更新。时间复杂度为O(n+mlogn),其中m,n分别为s和t的长度。
代码:
class Solution {
public:
bool isSubsequence(string s, string t) {
if(s.empty())
return true;
unordered_map<int, vector<int>> m;
int pre = -1, lent = t.size(), lens = s.size();
for(int i = 0; i < lent; i++)
m[t[i] - 'a'].push_back(i);
for(int i = 0; i < lens; i++)
{
auto it = upper_bound(m[s[i] - 'a'].begin(), m[s[i] - 'a'].end(), pre);
if(it == m[s[i] - 'a'].end())
return false;
pre = *it;
}
return true;
}
};