[Two Pointers, Easy] Is Subsequence

송재호·2025년 3월 11일
0

https://leetcode.com/problems/is-subsequence/description/?envType=study-plan-v2&envId=leetcode-75

투포인터로 t를 순회하면서 매치되는 글자가 있는 경우 sIndex를++한다.
최종적으로 sIndex == s.length()면 매치되는 순서대로 탐색을 완료했다는 뜻이므로 정답 조건이 된다.

다만 탐색 불가능한 경우에는 바로 break - 예를 들어 sIndex가 s의 길이 범위를 벗어남

class Solution {
    public boolean isSubsequence(String s, String t) {
        if (s.length() > t.length()) return false;

        int sIndex = 0;
        for (char c : t.toCharArray()) {
            if (sIndex >= s.length()) break;
            if (c == s.charAt(sIndex)) {
                sIndex++;
            }
        }

        return sIndex == s.length();
    }
}
profile
식지 않는 감자

0개의 댓글