问题描述
Given a string s and a string t, check if s is subsequence of t.
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).
判断字符串s
是否为t
的子序列。
子序列的定义:
你可以在原始字符串中删除一些字符,但是不能改变剩余字符之间的顺序。
举个例子:
Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false
解法1
思路如下:
首先,对于两个字符串分别定义起始变量sLo
和tLo
。
然后,遍历两个字符串,当任意字符串走到末尾,就可以结束循环,判断是否满足子序列。
那么在遍历过程中,需要做哪些事情?
如果t.charAt(tLo) == s.charAt(sLo)
,则两个变量分别+1
。
否则,仅tLo++
。
最后,判断sLo
是否等于字符串s
的长度。
来看下实现:
class Solution {
public boolean isSubsequence(String s, String t) {
int sLo = 0;
int sHi = s.length();
int tLo = 0;
int tHi = t.length();
while (sLo < sHi && tLo < tHi){
if (t.charAt(tLo) == s.charAt(sLo)){
sLo++;
}
tLo++;
}
return sLo == sHi;
}
}
Enjoy it !
一位喜欢提问、尝试的程序员
(转载本站文章请注明作者和出处 姚屹晨-yaoyichen)