392. Is Subsequence
1. 题目
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.
Follow up:
If there are lots of incoming S, say S1, S2, … , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
2. 题目分析
判断字符串s是否是t的子序列,要注意的是,这题与判断字符串s是否是t的子串不同之处在于,子序列是指在母串t中不需要连续的字符,而子串是需要连续的字符。比如说s = “abc”, t = “ahbgdc”,则s是t的子序列,但不是t的子串,因为在t中找不到一串完整字符串"abc"。
3. 解题思路
这题应该属于字符串问题,而不是动态规划问题,因为并不需要划分子问题解决,也没有需要找最优解。
判断子序列,虽然不需要连续,但需要保证s中的字符在t中相对的前后位置保证一致。比如说s = “abc”, t = “hbgadc”,则s不是t的子序列。所以这题只要使用两个指针,分别指向s和t中的遍历的位置,然后比较两则字符是否相同,相同,则两个指针都往后移动;不同,则只要移动t的指针。
4. 代码实现(java)
package com.algorithm.leetcode.dynamicAllocation;
/**
* Created by 凌 on 2019/1/29.
* 注释:392. Is Subsequence
*/
public class IsSubsequence {
public static void main(String[] args) {
String s = "";
String t = "";
System.out.println(s.equals(t));
}
/**
* 判断字符串s是否是t的子序列
* @param s
* @param t
* @return
*/
public boolean isSubsequence(String s, String t) {
if (s.length() == 0){
return false;
}
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();
int countS = 0;
int countT = 0;
while (countS < ss.length && countT < tt.length){
if (tt[countT] == ss[countS]){
countT++;
countS++;
}else{
countT++;
}
}
if (countS == ss.length){
return true;
}else{
return false;
}
}
}

本文深入探讨了LeetCode上的392.IsSubsequence问题,详细解释了如何判断一个字符串是否为另一个字符串的子序列,提供了清晰的解题思路和Java代码实现。

340

被折叠的 条评论
为什么被折叠?



