일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
- 스파크
- Python
- Hadoop
- 데이터 엔지니어링
- 오블완
- 분산
- 리트코드
- HDFS
- Data Engineering
- 티스토리챌린지
- 분산처리
- heapq
- 빅데이터
- 도커
- docker
- leetcode
- 아파치 하둡
- 알고리즘
- 딕셔너리
- 우선순위큐
- Spark
- 아파치 스파크
- 파이썬
- programmers
- 코딩테스트
- Apache Spark
- 프로그래머스
- 하둡
- Apache Hadoop
- 이진탐색
- Today
- Total
래원
[LeetCode] 2825. Make String a Subsequence Using Cyclic Increments (Python) 본문
[LeetCode] 2825. Make String a Subsequence Using Cyclic Increments (Python)
Laewon Jeong 2024. 12. 5. 14:50
난이도: Medium
문제 설명
You are given two 0-indexed strings str1 and str2.
In an operation, you select a set of indices in str1, and for each index i in the set, increment str1[i] to the next character cyclically. That is 'a' becomes 'b', 'b' becomes 'c', and so on, and 'z' becomes 'a'.
Return true if it is possible to make str2 a subsequence of str1 by performing the operation at most once, and false otherwise.
Note: A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.
문제 예제
Example 1:
Input: str1 = "abc", str2 = "ad"
Output: true
Explanation: Select index 2 in str1.
Increment str1[2] to become 'd'.
Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.
Example 2:
Input: str1 = "zc", str2 = "ad"
Output: true
Explanation: Select indices 0 and 1 in str1.
Increment str1[0] to become 'a'.
Increment str1[1] to become 'd'.
Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.
Example 3:
Input: str1 = "ab", str2 = "d"
Output: false
Explanation: In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once.
Therefore, false is returned.
제한 사항
- 1 <= str1.length <= 10^5
- 1 <= str2.length <= 10^5
- str1 and str2 consist of only lowercase English letters.
✏️ Solution(솔루션)
class Solution:
def canMakeSubsequence(self, str1: str, str2: str) -> bool:
i, j = 0, 0
n1 = len(str1)
n2 = len(str2)
while i != n1 and j != n2:
next_alpha = chr(ord(str1[i])+1) if str1[i] != 'z' else 'a'
if str1[i] == str2[j] or next_alpha == str2[j]:
j += 1
i+=1
if j == n2:
return True
return False
str1의 요소를 가리키는 i와 str2의 요소를 가리키는 j를 만들었다.
그 후 str1[i]의 요소를 str2[j]의 요소와 비교를 진행했다.
이때 str1[i] == str2[j]이거나, str1[i]의 다음 알파벳이랑 ('a' 이면 'b') str2[j]랑 같으면 j에 +1을 해주었다.
i는 매 반복문마다 +1을 해주었다.
반복문이 끝났을 때, j가 str2의 길이와 같으면 True를 반환하고 아니면 False를 반환했다.
Two Pointer에 대해 알고있으면 어렵지 않게 풀 수 있는 문제였다.
[LeetCode] 2825. Make String a Subsequence Using Cyclic Increments