CodeWars 마흔 두 번째 문제

Updated:

Count the smiley faces!

public static int countSmileys(List<String> arr) {

    int validFaceCount = 0;

    for(String face : arr) {
        validFaceCount += isValidFaceCount(face);
    }

    return validFaceCount;
}

private static int isValidFaceCount(String face) {
	
    if(face.length() == 2 && isVaildEye(face) && isVaildMouth(face,1,2)) {
        return 1;
    }

    if(face.length() == 3 && isVaildEye(face) && isVaildNose(face) &&isVaildMouth(face,2,3)) {
        return 1;
    }

    return 0;
}

public static boolean isVaildEye(String face) {
    return ":;".contains(face.substring(0,1));
}

public static boolean isVaildNose(String face) {
    return "-~".contains(face.substring(1,2));
}

public static boolean isVaildMouth(String face, int i, int j) {
    return ")D".contains(face.substring(i,j));
}
  • 나름 리펙토링으로 쉽게 알아 볼 수 있도록 짰다고 생각했다.

  • 하지만 Best 코드는 더 간결했다.

  • 두 번째 하지만 정규식을 이용해서 간결했다.

  • mathces는 주어진 정규식 인자값이랑 매칭되면 true를 return 한다.

  • [:;] [-~]? [)D] 의 의미는 smile에 [ ]사이에 있는 문자열중 포함되면 되는 뜻인데 [ ]가 3개 있으니 세 글자를 비교한다는 뜻이고 가운데 ?의 경우 두번 째 [ ]를 비교할 때는 - or ~가 있어도 되고 없어도 된다는 뜻!

public static int countSmileys(List<String> arr) {
    String validSmileRegExp = "[:;][-~]?[)D]";
    int smiles = 0;
    for (String smile : arr) {
        if (smile.matches(validSmileRegExp)) {
            smiles += 1; 
        }
    }
    return smiles;
}