[LeetCode / Easy] 392. Is Subsequence (Java)

이하얀·2025년 3월 9일
0

📙 LeetCode

목록 보기
13/13

💬 Info



Problem

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

예시 2

  • Input: s = "axc", t = "ahbgdc"
  • Output: false

Constraints

  • 0 <= s.length <= 100
  • 0 <= t.length <= 10410^4
  • s and t consist only of lowercase English letters.


문제 이해

  • 두 문자열 s와 t -> s가 t 부분 문자열이면 true, 그렇지 않은 경우 false 반환하기


알고리즘

풀이 시간 : 10분

  • s의 문자가 t에 순서대로 등장하는지 확인
  • t를 순회하면서 s의 현재 문자가 일치하면 index 증가
  • index가 s.length()와 같아지면 true, 아니면 false
class Solution {
    public boolean isSubsequence(String s, String t) {
        int index = 0;
        
        for (char c : t.toCharArray()) {
            if (index < s.length() && s.charAt(index) == c) {
                index++;
            }
        }
        
        return index == s.length();
    }
}


결과

profile
언젠가 내 코드로 세상에 기여할 수 있도록, Data Science&BE 개발 기록 노트☘️

0개의 댓글