코린이의 소소한 공부노트

[LeetCode/Easy] 2047. Number of Valid Words in a Sentence 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 2047. Number of Valid Words in a Sentence

무지맘 2023. 4. 26. 00:53

1. Input

1) String sentence

- sentence1개 이상의 공백 문자로 구분되는 1개 이상의 토큰으로 쪼개질 수 있다.

 

2. Output

1) 다음 조건을 만족하는 토큰의 개수를 반환

- 숫자는 포함하지 않아야 한다.

- 하이픈(-)은 최대 1개까지 있을 수 있으며, 반드시 영어 소문자로 둘러싸여 있어야 한다.

- 문장부호는 최대 1개까지 있을 수 있으며, 만약 있다면 토큰의 맨 끝에 있어야 한다.

 

3. Constraint

1) 1 <= sentence.length <= 1000

2) sentence는 영어 소문자, 숫자, 공백 문자, 특수문자 -!,.로 이루어져 있다.

3) 토큰은 최소 1개 있다.

 

4. Example

Input: sentence = "alice and bob are playing stone-game10" -> Output: 5

설명: 6개의 토큰이 있다. 이중 유효하지 않은 토큰은 "stone-game10"이며, 이유는 숫자가 포함되어있기 때문이다.

 

5. Code

1) 첫 코드(2023/04/26)

import java.util.*;
class Solution {
    public int countValidWords(String sentence) {
        StringTokenizer token = new StringTokenizer(sentence);
        int count = token.countTokens();
        while(token.hasMoreTokens()){
            String s = token.nextToken();
            for(int i=0 ; i<s.length() ; i++){                
                char c = s.charAt(i);
                if(Character.isDigit(c)){
                    count--; break;
                }
                if(c=='-' && !s.matches("[a-z]+-[a-z]+[//.!,]?")){
                    count--; break;
                }
                if((c=='!' || c=='.' || c==',') && i!=s.length()-1){
                    count--; break;
                }
            }
        }
        return count;
    }
}