프로그래밍 면접 책

특정 문자의 제거

AsCE_hyunseung 2018. 12. 5. 05:47

문제

- 문자열에서 문자를 효율적으로 삭제하는 함수를 작성하라. 함수 원형은 다음과 같다

String removeChars(String str, String remove);

 remove라는 인자로 전달된 문자열에 있는 모든 문자를 str이라는 문자열에서 삭제한다.

예를 들어 str이 "Battle of the Vowels: Hawaii vs. Grozny"로 주어지고 remove가 "aeiou"로 주어진다면 이 함수에서 str에서 str을 "Bttl f th Vwls: Hw vs. Grzny"로 변환시켜야 한다. 자신이 함수를 설계한 방식에 대해 합당한 근거를 제시하고 풀이의 효율에 대해 논하라.


처음 문제를 보고 앞에 문제(반복되지 않는 첫 번째 문자 찾기)에서 썼던 해시를 이용해서 풀어보려고 만지작 거리다가 문득 생각해보니까 replace()함수를 쓰면 시간복잡도는 O(n)을 유지하면서 코드는 간편하게 풀 수 있을 것 같다 생각했다.(추후에 방식이 너무 날로 먹는다 싶으면 코드 리뷰받고 다시 풀어보도록 해야겠다.)


RemoveChars.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class RemoveChars {
    String solution(String str,String remove){
        String [] reject=remove.split("");//제거해야할 알파벳들을 한글자씩 분리
 
        return rejectElement(str, reject);
    }
 
    private String rejectElement(String str, String[] reject) {
        for(String s:reject){
            str=str.replace(s,"");//replace()함수를 이용해서 해당 알파벳만 제거
        }
        return str;
    }
}
cs


RemoveCharsTest.java

1
2
3
4
5
6
7
8
9
10
import org.junit.Test;
import static org.junit.Assert.*;
 
public class RemoveCharsTest {
    RemoveChars r= new RemoveChars();
    @Test
    public void 테스트_결과() {
        assertEquals("Bttl f th Vwls: Hw vs. Grzny",r.solution("Battle of the Vowels: Hawaii vs. Grozny","aeiou"));
    }
}
cs