Number of Valid Words in a Sentence LeetCode solution in Java
1class Solution {2public int countValidWords(String sentence) {3String regex = "^([a-z]+(-?[a-z]+)?)?(!|\\.|,)?$";4String r2 = "[^0-9]+";5String[] arr = sentence.split("\\s+");6int ans = 0;7for (String s : arr) {8if (s.matches(regex) && s.matches(r2)) {9ans++;10// System.out.println(s);11}12}13return ans;14}15}