[LeetCode] 392 Is Subsequence

황은하·2021년 5월 21일
0

알고리즘

목록 보기
39/100
post-thumbnail

Description

Given two strings s and t, check if s is a subsequence of t.

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

Example 2:

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

Constraints:

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

Follow up:

If there are lots of incoming s, say s1, s2, ..., sk where k >= 10^9, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?


풀이

  • 문자열 s가 문자열 t에 문자 순서까지 동일한 상태로 들어가 있는지 파악하는 문제이다.
    t에 없는 문자가 들어있거나, s의 문자들의 순서가 t와 다르다면 false를 반환한다.
  • s가 아무것도 입력되지 않으면 순서가 상관이 없고, t의 어디든 들어갈 수 있으니 true를 반환했다.
  • t를 한 문자씩 잘라서 배열에 저장한다.
  • for문을 통해 s의 앞에서부터 한 문자씩 순서대로 검사한다.
    t의 문자를 처음부터 끝까지 보면서 s의 문자가 들어있다면 s의 다음 문자로 넘어간 뒤 count를 1 증가시켰다. 만약 검사할 s가 마지막 문자이며 t에 포함될 경우 count를 1 증가시킨 뒤 for문을 빠져나온다.
  • 마지막으로 count가 s의 길이와 같다면 s의 모든 문자가 순서대로 t에 포함되었으므로 true를 반환하고 아닐 경우 false를 반환한다.


코드

class Solution {
    public boolean isSubsequence(String s, String t) {
        if (s.length() == 0) return true;

        String[] arr = t.split("");
        int index = 0, count = 0;
        String sub = String.valueOf(s.charAt(index++));

        for (int i = 0; i < t.length(); i++) {
            if (sub.equals(arr[i])) {
                if (index == s.length()) {
                    count++;
                    break;
                }
                sub = String.valueOf(s.charAt(index++));
                count++;
            }
        }

        if (count == s.length()) return true;
        else return false;
    }
}
profile
차근차근 하나씩

0개의 댓글