题解 | #特工的密码#
特工的密码
https://www.nowcoder.com/practice/bcdfed09de534aea92b24c73699dba5c
知识点:双指针
题目要求找到子序列,也就是不要求连续,可以使用双指针的思想,两个指针分别指向两个字符串中未遍历到的位置,我们可以对t字符串进行遍历,如遇到s字符串中的第一个未遍历到的字符,则将i指针右移一位,当i指针遍历了整个s字符串,说明含有子序列,即可返回true。
Java题解如下
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param t string字符串 * @return bool布尔型 */ public boolean isSubsequence (String s, String t) { // write code here int i = 0, j = 0; while(j < t.length()) { if(t.charAt(j++) == s.charAt(i)) { i++; if(i == s.length()) { return true; } } } return false; } }