392.判断子序列

给定字符串 st ,判断 s 是否为 t 的子序列。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace""abcde"的一个子序列,而"aec"不是)。

思路:

双指针分别指向两个个字符串,相同则一起移动,不同则移动主串指针,直到主串指针移动到最后。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.wereash.scut_hot100;

import java.util.Scanner;

/**
* @Author: WereAsh
* @Date:2026-01-15 19:06
**/
public class Solution392 {
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
String s=scanner.nextLine();
String t=scanner.nextLine();
int i=0,m=s.length();
int j=0,n=t.length();
while(i<m&&j<n){
if(s.charAt(i)==t.charAt(j)){
i++;
}
j++;
}
if(i==s.length()){
System.out.println("true");
}
else {
System.out.println("false");
}
}
}