Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
Find the leftmost occurrence of the substring part and remove it from s.
Return s after removing all occurrences of part.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "daabcbaabcbc", part = "abc"
Output: "dab"
Explanation: The following operations are done:
- s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc".
- s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".
- s = "dababc", remove "abc" starting at index 3, so s = "dab".
Now s has no occurrences of "abc".
Example 2:
Input: s = "axxxxyyyyb", part = "xy"
Output: "ab"
Explanation: The following operations are done:
- s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb".
- s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb".
- s = "axxyyb", remove "xy" starting at index 2 so s = "axyb".
- s = "axyb", remove "xy" starting at index 1 so s = "ab".
Now s has no occurrences of "xy".
문자열에서 특정 문자열을 반복해서 지우는 방법
StringBuilder에서 indexOf("word") 라는 메서드를 사용하면 word가 시작하는 첫 index를 리턴해준다.
그 뒤에, sb.delete(index, index + word.length()) 를 사용하면 해당 문자열을 삭제할 수 있다.
정답 코드
class Solution {
public String removeOccurrences(String s, String part) {
StringBuilder sb = new StringBuilder(s);
int idx = sb.indexOf(part);
while (idx != -1) {
System.out.println(idx);
sb.delete(idx, idx + part.length());
idx = sb.indexOf(part); // 계속 갱신
}
return sb.toString();
}
}
스택을 사용하여 풀이를 시도했는데, 다소 복잡했다.
StringBuilder 메서드를 사용하니 정말 간단하게 풀렸다.
'Algorithm > Leetcode' 카테고리의 다른 글
3/24 풀이 (0) | 2025.03.24 |
---|---|
2467. Most Profitable Path in a Tree (0) | 2025.03.03 |
1834. Single-Threaded CPU (0) | 2025.01.31 |
2381. Shifting Letters II (0) | 2025.01.22 |
1589. Maximum Sum Obtained of Any Permutation (0) | 2025.01.22 |