[LeetCode] 2825. Make String a Subsequence Using Cyclic Increments (Python)

2024. 12. 5. 14:50·알고리즘/LeetCode

 

난이도: 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

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] 2054. Two Best Non-Overlapping Events (Python)  (0) 2024.12.09
[LeetCode] 2554. Maximum Number of Integers to Choose From a Range I (Python)  (0) 2024.12.06
[LeetCode] 2109. Adding Spaces to a String - Python  (0) 2024.12.03
[LeetCode] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence - Python  (0) 2024.12.02
[LeetCode] 1346. Check If N and Its Double Exist - Python  (0) 2024.12.01
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 2054. Two Best Non-Overlapping Events (Python)
  • [LeetCode] 2554. Maximum Number of Integers to Choose From a Range I (Python)
  • [LeetCode] 2109. Adding Spaces to a String - Python
  • [LeetCode] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence - Python
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    쿠버네티스
    Apache Spark
    도커
    docker
    dfs
    String
    분산
    heapq
    DP
    leetcode
    파이썬
    오블완
    Kubernetes
    백트래킹
    리트코드
    문자열
    BFS
    우선순위큐
    이진탐색
    그래프
    분산처리
    아파치 하둡
    Python
    누적합
    아파치 스파크
    알고리즘
    코딩테스트
    프로그래머스
    티스토리챌린지
    programmers
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 2825. Make String a Subsequence Using Cyclic Increments (Python)
상단으로

티스토리툴바