给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是),并写出代码。
时间: 2024-02-13 12:02:37 浏览: 14
以下是判断 s 是否为 t 的子序列的 Python 代码:
```python
def isSubsequence(s: str, t: str) -> bool:
if len(s) == 0:
return True
i = 0
for j in range(len(t)):
if s[i] == t[j]:
i += 1
if i == len(s):
return True
return False
```
该代码使用双指针算法,分别在字符串 s 和 t 上移动指针 i 和 j,如果 s[i] 和 t[j] 相等,则 i 和 j 都向后移动一位,否则只移动 j。最终如果 i 等于 s 的长度,则 s 是 t 的子序列,返回 True,否则返回 False。
相关问题
给定两个字符串s和t判断s是否是t的子序列
题目描述:
给定两个字符串 s 和 t ,判断 s 是否为 t 的子序列。
示例:
s = "abc", t = "ahbgdc",返回 true
s = "axc", t = "ahbgdc",返回 false
思路:
遍历字符串 t,如果字符与 s 中的字符相同,则 s 中指针后移,直到 s 遍历完,返回 true。如果 t 遍历完,s 还没有遍历完,返回 false。
Python代码:
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i, j = 0, 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
return i == len(s)
C语言给定两个字符串s和t判断s是否是t的子序列
思路:
- 定义两个指针i和j,分别指向s和t的开头。
- 遍历t,如果当前字符等于s的字符,则i和j同时后移;否则只将j后移。
- 如果i指针到达了s的末尾,则s是t的子序列;否则如果j指针到达了t的末尾,则s不是t的子序列。
代码实现:
```c
bool isSubsequence(char * s, char * t){
int i = 0, j = 0;
while (s[i] && t[j]) {
if (s[i] == t[j]) {
i++;
j++;
} else {
j++;
}
}
return !s[i];
}
```
时间复杂度:$O(n)$,其中$n$为$t$的长度。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)