December 10, 2025
์ด ๋ฌธ์ ๋ ๋ค์ ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์๋ฆ๋ค์ด ์ธ๋ฑ์ค์ ๊ฐ์๋ฅผ ์ฐพ๋ ๋ฌธ์ ์ ๋๋ค.
์ฆ, ์๋ฆ๋ค์ด ์กฐ๊ฑด์ ๋ค์๊ณผ ๊ฐ๋ค:
์ด๋ ๊ฒ ํ์ ๋ ํ๋ฆฌ๊ธฐ๋ ํ์ง๋ง ์๊ฐ ๋ณต์ก๋๊ฐ O(N^2)์ผ๋ก ๋นํจ์จ์ ์ผ ์ ์์ต๋๋ค.
class Solution:
def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]:
na, nb = len(a), len(b)
a_indices = []
b_indices = []
for i in range(len(s)):
# find indexes of occurrences str a
if i+na<=len(s) and s[i:i+na]==a:
a_indices.append(i)
# find indexes of occurrences str b
if i+nb<=len(s) and s[i:i+nb]==b:
b_indices.append(i)
ans = []
for i in a_indices:
for j in b_indices:
if abs(j-i) <= k:
ans.append(i)
break
return ans
๋ฐ๋ผ์, ๋๋ฒ์งธ ๋ถ๋ถ์ ์ด์ค for๋ฌธ์ ๋์ ํ์ฌ bisect๋ฅผ ์ฐ๋ฉด O(N)์ O(N log N)์ผ๋ก ์ค์ผ ์ ์์ต๋๋ค.
class Solution:
def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]:
na, nb = len(a), len(b)
a_indices = []
b_indices = []
for i in range(len(s)):
# find indexes of occurrences str a
if i+na<=len(s) and s[i:i+na]==a:
a_indices.append(i)
# find indexes of occurrences str b
if i+nb<=len(s) and s[i:i+nb]==b:
b_indices.append(i)
ans = []
for i in a_indices:
for j in b_indices:
if abs(j-i) <= k:
ans.append(i)
break
return ans
Constraints:
1 <= k <= s.length <= 10^5
1 <= a.length, b.length <= 10
s, a, and b contain only lowercase English letters.