LeetCode刷题实战392:判断子序列
共 2035字,需浏览 5分钟
·
2021-09-27 07:17
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
示例
示例 1:
输入:s = "abc", t = "ahbgdc"
输出:true
示例 2:
输入:s = "axc", t = "ahbgdc"
输出:false
解题
class Solution {
public boolean isSubsequence(String s, String t) {
int n = s.length(), m = t.length();
int i = 0, j = 0; //i -> s , j -> t
while(i < n && j < m){
if(s.charAt(i) == t.charAt(j)) i++; // 相等时,i++
j++; // 不管是否相等,j++
}
return i == n ;
}
}
LeetCode刷题实战381:O(1) 时间插入、删除和获取随机元素