mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 392. Is Subsequence.md
This commit is contained in:
parent
e21ca2bc7b
commit
23e15c7253
53
solutions/392. Is Subsequence.md
Normal file
53
solutions/392. Is Subsequence.md
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
# [392. Is Subsequence](https://leetcode.com/problems/is-subsequence/)
|
||||||
|
|
||||||
|
# 思路
|
||||||
|
题目要求判断字符串s是否是字符串t的子序列。
|
||||||
|
|
||||||
|
## 思路一
|
||||||
|
这题是个easy题,基本思想确实很简单,我们可以用两个指针p1和p2分别作用于s和t。然后不断右移指针进行匹配。
|
||||||
|
|
||||||
|
时间复杂度O(n),空间复杂度O(1)
|
||||||
|
|
||||||
|
## 思路二
|
||||||
|
|
||||||
|
题目还问如果有源源不断的s进来且每次t都是保持不变的,那么函数该如何优化。为了能快速定位某个字符在t中的位置,我们可以考虑有hash,
|
||||||
|
由于同一个字符可能在t中出现了多次,所以这个hash是字符到数组的映射。
|
||||||
|
对于s中的每个字符s[i],假设s[i-1]对应t中匹配位置是pre,那么我们查找s[i]在t中出现的位置中第一个大于pre的位置,这可用二分查找upper_bound.
|
||||||
|
|
||||||
|
|
||||||
|
# C++
|
||||||
|
## 思路一
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
bool isSubsequence(string s, string t) {
|
||||||
|
int p1 = 0, p2 = 0;
|
||||||
|
// if(s.size() > t.size()) return false;
|
||||||
|
while(p1 < s.size() && p2 < t.size()){
|
||||||
|
while(p2 < t.size() && t[p2] != s[p1]) p2++;
|
||||||
|
p1++; p2++;
|
||||||
|
}
|
||||||
|
return (p1 == s.size() && p2 <= t.size());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## 思路二
|
||||||
|
``` C++
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
bool isSubsequence(string s, string t) {
|
||||||
|
unordered_map<char, vector<int>>mp;
|
||||||
|
for(int i = 0; i < t.size(); i++)
|
||||||
|
mp[t[i]].push_back(i);
|
||||||
|
|
||||||
|
int pre = -1;
|
||||||
|
for(char &c: s){
|
||||||
|
auto it = upper_bound(mp[c].begin(), mp[c].end(), pre);
|
||||||
|
if(it == mp[c].end()) return false; // 查找失败
|
||||||
|
pre = *it; // 更新pre
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user