본문 바로가기
알고리즘

[LeetCode/JAVA] 1684. Count the Number of Consistent Strings

by 상후 2021. 9. 4.
728x90
반응형

 

 

https://github.com/ROUTINE-STUDY/Algorithm

알고리즘 스터디를 진행하고 있습니다. 😊
초보들로 구성되어있으며, 열심히 풀어보고 풀이 방식을 공유하고 피드백을 해주는 스터디입니다.
참여 문의는 댓글 혹은 GitHub 주소를 참고해주세요.

문제 출처 : https://leetcode.com/problems/count-the-number-of-consistent-strings/

 

Count the Number of Consistent Strings - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 설명

출처 : LeetCode

allowed 문자열로만 구성된 words 배열 내 문자열의 개수를 반환하세요.

 

풀이 방법
다양한 방법이 존재할 것 같습니다.

1. 정규표현식을 이용한 풀이 방법
2. 일반적인 for문과 contains 메서드를 이용한 풀이 방법

위 두 가지 방법으로 풀어보았습니다. 다른 방법도 많이 존재하니 생각해보면 좋을 것 같습니다.

 

내 코드(JAVA)

 

public class Solution {

    // 1. 정규표현식을 이용한 방식
    public int countConsistentStrings_regex(String allowed, String[] words) {
        int result = 0;

        for(String word : words) {
            if(word.matches("^[" + allowed + "]*$")) {
                result++;
            }
        }
        return result;
    }

    // 2. 반복문 및 contains 메서드 이용
    public int countConsistentStrings_contains(String allowed, String[] words) {
        int result = 0;

        for(String word : words) {
            boolean isContain = true;

            for(char ch : word.toCharArray()) {
                if(!allowed.contains(String.valueOf(ch))) {
                    isContain = false;
                    break;
                }
            }

            if(isContain) result++;
        }
        return result;
    }

}

 

 

 

728x90
반응형

댓글