392. Is Subsequence
2026/1/12大约 1 分钟约 405 字
392. Is Subsequence
难度: Easy
题目描述
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).
Example 1:
Input: s = "abc", t = "ahbgdc" Output: true
Example 2:
Input: s = "axc", t = "ahbgdc" Output: false
Constraints:
0 <= s.length <= 1000 <= t.length <= 104sandtconsist only of lowercase English letters.
Follow up: Suppose there are lots of incoming
s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code? 解题思路
代码实现
解决方案
java
class Solution {
public static final Map<String,Map<Character, TreeSet<Integer>>> tMap = new HashMap<>();
public boolean isSubsequence(String s, String t) {
if("".equals(s)){
return true;
}
Map<Character, TreeSet<Integer>> map = tMap.get(t);
if(map == null){
map = new HashMap<>();
for(int i = 0; i < t.length(); i++) {
char c = t.charAt(i);
if(!map.containsKey(c)) {
map.put(c, new TreeSet<>());
}
map.get(c).add(i);
}
tMap.put(t, map);
}
Integer preIndex = t.indexOf(s.charAt(0));
if (preIndex < 0) {
return false;
}
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (!map.containsKey(c)) {
return false;
}
TreeSet<Integer> set = map.get(c);
Integer targetData = set.higher(preIndex);
if (targetData == null) {
return false;
}
preIndex = targetData;
}
return true;
}
}