https://leetcode.com/problems/remove-all-occurrences-of-a-substring/
Remove All Occurrences of a Substring - LeetCode
Remove All Occurrences of a Substring - 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 re
leetcode.com
풀이
StringBuilder 에 indexOf 메서드를 쓰면 part가 포함되어있는 idx를 알려준다. 없으면 -1 리턴.
-1 이 나올때까지 (포함되어있지 않을때까지) 반복문을 돌리면서 포함되어있으면 delete 해준다.
public static String removeOccurrences(String s, String part) {
StringBuilder sb = new StringBuilder(s);
while (sb.indexOf(part) != -1) {
sb.delete(sb.indexOf(part), sb.indexOf(part) + part.length());
}
return sb.toString();
}
'algorithm > leetcode' 카테고리의 다른 글
leetcode 1004. Max Consecutive Ones III (JAVA) (1) | 2023.02.04 |
---|---|
LeetCode 45. Jump Game II (JAVA) (0) | 2023.01.24 |
LeetCode 162. Find Peak Element (JAVA) (0) | 2023.01.24 |
LeetCode 165. Compare Version Numbers (JAVA) (1) | 2023.01.13 |
LeetCode 383. Ransom Note (JAVA) (1) | 2023.01.13 |