문제
내가 작성한 정답
class Solution {
public int solution(String[] babbling) {
int answer = 0;
String[] bb = {"aya", "ye", "woo", "ma"};
for (String s : babbling) {
for (String b : bb) {
s = s.replace(b, " ");
}
if (s.trim().isEmpty()) {
answer++;
}
}
return answer;
}
}
다른 사람들의 정답
정규식 사용 + 연속된 같은 단어가 나오면 안 된다는 조건
class Solution {
public int solution(String[] babbling) {
int answer = 0;
for (String s : babbling) {
if (s.matches("^(aya|ye|woo|ma)+$")) {
answer++;
}
}
return answer;
}
}

정규식 사용 + 연속된 같은 단어가 나오면 안 된다는 조건
class Solution {
public int solution(String[] babbling) {
int answer = 0;
for(int i = 0; i < babbling.length; i++) {
// ^: 문자열의 시작.
// (...)+: 괄호 안의 패턴이 하나 이상 반복될 수 있음
// aya(?!aya): aya가 뒤에 또 다른 aya가 오지 않는 경우. 즉, aya가 연속되지 않아야 한다
// ye(?!ye), woo(?!woo), ma(?!ma): 각각 ye, woo, ma에 대해서도 같은 조건을 적용
// $: 문자열의 끝.
if(babbling[i].matches("^(aya(?!aya)|ye(?!ye)|woo(?!woo)|ma(?!ma))+$")) {
answer++;
}
}
return answer; // 조건을 만족하는 문자열의 개수를 반환
}
}
matches() 메서드
boolean result = s.matches("정규표현식");
System.out.println("hello".matches("hello")); // true
System.out.println("hello world".matches("hello")); // false
• 문자열 s가 정규 표현식 패턴과 완전히 일치하는지 검사.
• 부분 일치는 허용되지 않음, 전체 문자열이 정규식과 일치해야 true를 반환.
Share article