일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- concurrency
- Python
- attribute
- DWG
- data science
- Decorator
- Substring with Concatenation of All Words
- iterator
- Regular Expression
- 315. Count of Smaller Numbers After Self
- Python Code
- 43. Multiply Strings
- Class
- 시바견
- kaggle
- shiba
- 프로그래머스
- Protocol
- t1
- Generator
- LeetCode
- 운영체제
- 파이썬
- Python Implementation
- 밴픽
- Convert Sorted List to Binary Search Tree
- 715. Range Module
- 컴퓨터의 구조
- 109. Convert Sorted List to Binary Search Tree
- 30. Substring with Concatenation of All Words
Archives
- Today
- Total
Scribbling
LeetCode: 833. Find And Replace in String 본문
Computer Science/Coding Test
LeetCode: 833. Find And Replace in String
focalpoint 2022. 3. 15. 09:48The very first thing to do is looking for matches.
We don't need to use any fancy algorithms when looking for matches in this problem because it is guranteed that replacements will not overlap.
Now we have matched list in the form of [index, source, target].
If you are planning to replace s directly, it will lead to bad time complexity as you will have to copy all the characters of s each time you replace a word. --> O(len(s) * num_replacements) ~= 1000 * 100 in this prob
So we use list(strList) instead. We chop the string into the list while replacing source with target at the same time.
* matched.sort() is necessary when matched index are not in ascending order.
Below is the code.
class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
# [index, source, target]
matched = []
k = len(indices)
for i in range(k):
idx, source, target = indices[i], sources[i], targets[i]
# match?
if s[idx:idx+len(source)] == source:
matched.append((idx, source, target))
matched.sort()
strList, prv = [], 0
for idx, source, target in matched:
strList.append(s[prv:idx])
strList.append(target)
prv = idx + len(source)
strList.append(s[prv:])
return ''.join(strList)
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 2034. Stock Price Fluctuation (0) | 2022.03.23 |
---|---|
LeetCode: 715. Range Module (0) | 2022.03.18 |
LeetCode: 772. Basic Calculator III (0) | 2022.03.11 |
LeetCode: 745. Prefix and Suffix Search (0) | 2022.03.10 |
LeetCode: 1834. Single-Threaded CPU (0) | 2022.03.08 |