250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code c++)Is Subsequence 본문
728x90
반응형
392. Is Subsequence
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 <= 104
- s and t consist only of lowercase English letters.
주어진 문자열 s와 t가 있다.
t의 subsequence로 s가 존재하는지 여부를 확인하면 된다.
s의 인덱스를 나타내는 sIndex를 선언,
t를 for문으로 순회하면서 sIndex에 해당하는 단어가 있으면 sIndex++.
for문이 끝나고 만약 sIndex가 s.size()와 같다면 t의 subsequence로 s가 존재한다는 뜻이므로 true 리턴.
아니라면 false 리턴.
class Solution {
public:
bool isSubsequence(string s, string t) {
int sIndex = 0;
for(int i = 0; i < t.size(); i++){
if(s[sIndex] == t[i]){
sIndex++;
}
}
return sIndex == s.size() ? true : false;
}
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)Merge k Sorted Lists (0) | 2021.09.10 |
---|---|
(Leet Code c++)Longest Palindrome (0) | 2021.09.08 |
(Leet Code JS)Island Perimeter (0) | 2021.09.06 |
(Leet Code JS)Validate Binary Search (0) | 2021.09.06 |
(Leet Code JS)Find the Difference (0) | 2021.09.04 |