출처: https://leetcode.com/problems/is-subsequence/
문제
한글 번역은 아래 더보기를 클릭해주세요.
더보기
문자열 s와 t가 주어졌을 때, s가 t의 부분문자열인지 구하여라.
어떤 문자열의 부분문자열이란, 어떤 문자열 내 문자들의 상대적인 순서 변경없이 일부를 삭제하여(삭제하지 않을 수도 있음) 얻을 수 있는 문자열을 말한다. (예, ace는 abcde의 부문문자열이다. aec는 abcde의 부분문자열이 아니다)
예제1:
- 입력: s="abc", t="ahbgdc"
- 출력: true
예제2:
- 입력: s="axc", t="ahbgdc"
- 출력: false
제약조건:
- 0 < s.length < 100
- 0 < t.length < 10^4
- s와 t는 영문소문자로만 구성되어 있다
풀이
해결방법
if (s.length >= t.length) return s == t
순회하면서 비교
javascript
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isSubsequence = function(s, t) {
// s의 길이가 t의 길이보다 길면 false
if (s.length > t.length) {
return false;
}
// s의 길이가 t의 길이와 같으면 s === t인 지 비교
if (s.length === t.length) {
return s === t;
}
let i = 0;
let j = 0;
while (i < s.length && j < t.length) {
if (s[i] === t[j]) {
i += 1
}
j += 1
}
return i === s.length;
};
python
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if len(s) > len(t):
return False
if len(s) == len(t):
return s == t
i = 0
j = 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
return i == len(s);
결과
'CS기초 > 코딩테스트' 카테고리의 다른 글
LeetCode 349 (Easy) Intersection of Two Arrays (0) | 2021.03.11 |
---|---|
LeetCode 278 (Easy) First Bad Version (0) | 2021.03.11 |
LeetCode 1710 (Easy) Maximum Units on a Truck (0) | 2021.03.03 |
LeetCode 122 (Easy) Best Time to Buy and Sell Stock II (0) | 2021.03.03 |
LeetCode 1217 (Easy) Minimum Cost to Move Chips to The Same Position (0) | 2021.02.24 |