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();
}

 

+ Recent posts