本文共 841 字,大约阅读时间需要 2 分钟。
判断字符串s是否是另一个字符串t的子序列的方法是使用双指针遍历。一个指针遍历s,另一个遍历t。当两个指针指向相同字符时,s的指针前进。无论是否匹配,t的指针总是前进。当t的指针遍历完时,检查s的指针是否到达末尾。如果是,则s是t的子序列。
解题思路:
代码实现:
public class Solution { public boolean isSubsequence(String s, String t) { int lenS = s.length(); int lenT = t.length(); if (lenS > lenT) { return false; } int i = 0, j = 0; while (i < lenS && j < lenT) { if (s.charAt(i) == t.charAt(j)) { i++; } j++; } return i >= lenS; }} 代码解释:
i遍历s,j遍历t。这种方法高效且简洁,能够在O(n)时间复杂度内解决问题,适用于处理长字符串。
转载地址:http://jbxg.baihongyu.com/