package com.example.lettcode.dailyexercises;
/**
* @Class IsSubsequence
* @Description 392 判断子序列
* 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
* 你可以认为 s 和 t 中仅包含英文小写字母。
* 字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
* 字符串的一个子序列是原始字符串删除一些(也可以不删除)
* 字符而不改变剩余字符相对位置形成的新字符串。
* (例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
* <p>
* 示例 1:
* s = "abc", t = "ahbgdc"
* 返回 true.
* <p>
* 示例 2:
* s = "axc", t = "ahbgdc"
* 返回 false.
* @Author
* @Date 2020/7/14
**/
public class IsSubsequence {
}
/**
* 解法1:递归
*/
public static boolean isSubsequence(String s, String t) {
// s=="" 或者t=""??
if (s == null || t == null) return false;
return recur(s, 0, t, 0);
}
/**
* 递归:表示s[0..k-1] 均在t[..index-1]处找到对应的子序列
*/
public static boolean recur(String s, int k, String t, int index) {
// t字符串已到结尾,但没有找到s对应的子序列
if (k < s.length() && index >= t.length()) return false;
// s[0..k-1] 已找到对应的子序列
if (k == s.length()) return true;
// 判断当前位置s[k]与t[index]是否相等,相等比较两者的下一个位置的字符
// 否则s[k]将于t[index+1]进行比较
if (s.charAt(k) == t.charAt(index)) {
return recur(s, k + 1, t, index + 1);
}
return recur(s, k, t, index + 1);
}
/**
* 解法2:双指针,分别指向两个字符串
*/
public static boolean isSubsequence(String s, String t) {
if (s == null || t == null) return false;
int indexS = 0;
int indexT = 0;
while (indexS < s.length() && indexT < t.length()) {
if (s.charAt(indexS) != t.charAt(indexT)) {
indexT++;
continue;
}
indexS++;
indexT++;
}
if (indexS >= s.length()) return true;
return false;
}
// 测试用例
public static void main(String[] args) {
String s = "abc", t = "ahbgdc";
boolean ans = isSubsequence(s, t);
System.out.println("IsSubsequence demo01 result:" + ans);
s = "axc";
t = "ahbgdc";
ans = isSubsequence(s, t);
System.out.println("IsSubsequence demo02 result:" + ans);
s = "";
t = "ahbgdc";
ans = isSubsequence(s, t);
System.out.println("IsSubsequence demo03 result:" + ans);
s = "axc";
t = "";
ans = isSubsequence(s, t);
System.out.println("IsSubsequence demo04 result:" + ans);
}