Description
두 문자열 s와 t가 주어졌을 때 s가 t의 연속이면 true를 반환하고 그렇지 않으면 false를 반환한다.
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
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:
Suppose there are lots of incoming
has its subsequence. In this scenario, how would you change your code?
Solution 1. Two pointer
public boolean isSubsequence(String s, String t) {
if(s.length() == 0) return true;
int i = 0;
for (int j = 0; j < t.length(); j++) {
if(s.charAt(i) == t.charAt(j)){
if(++i==s.length()) return true;
}
}
return false;
}
두 개의 포인터를 이용하여 일치할 경우 s포인터를 하나씩 이동하고 s의 포인터가 마지막까지 이동했다면 true를 아니면 false를 반환합니다.
Reference
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 799. Champagne Tower - 문제풀이 (0) | 2022.03.05 |
---|---|
[LeetCode] 413. Arithmetic Slices - 문제풀이 (0) | 2022.03.04 |
[LeetCode] 338. Counting Bits - 문제풀이 (0) | 2022.03.02 |
[LeetCode] 228. Summary Ranges - 문제풀이 (0) | 2022.02.28 |
[LeetCode] 165. Compare Version Numbers - 문제풀이 (0) | 2022.02.25 |