Skip to content

2047. Number of Valid Words in a Sentence 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
 public:
  int countValidWords(string sentence) {
    int ans = 0;
    istringstream iss(sentence);

    for (string token; iss >> token;)
      if (isValid(token))
        ++ans;

    return ans;
  }

 private:
  bool isValid(const string& token) {
    int countHyphen = 0;
    for (int i = 0; i < token.length(); ++i) {
      const char c = token[i];
      if (isdigit(c))
        return false;
      if (c == '-') {
        if (i == 0 || !isalpha(token[i - 1]))
          return false;
        if (i + 1 == token.length() || !isalpha(token[i + 1]))
          return false;
        if (++countHyphen > 1)
          return false;
      } else if (c == '!' || c == '.' || c == ',') {
        if (i != token.length() - 1)
          return false;
      }
    }
    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
  public int countValidWords(String sentence) {
    int ans = 0;

    for (final String token : sentence.trim().split("\\s+"))
      if (isValid(token))
        ++ans;

    return ans;
  }

  private boolean isValid(final String token) {
    int countHyphen = 0;
    for (int i = 0; i < token.length(); ++i) {
      final char c = token.charAt(i);
      if (Character.isDigit(c))
        return false;
      if (c == '-') {
        if (i == 0 || !Character.isLowerCase(token.charAt(i - 1)))
          return false;
        if (i + 1 == token.length() || !Character.isLowerCase(token.charAt(i + 1)))
          return false;
        if (++countHyphen > 1)
          return false;
      } else if (c == '!' || c == '.' || c == ',') {
        if (i != token.length() - 1)
          return false;
      }
    }
    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def countValidWords(self, sentence: str) -> int:
    def isValid(token: str) -> bool:
      countHyphen = 0
      for i, c in enumerate(token):
        if c.isdigit():
          return False
        if c == '-':
          if i == 0 or not token[i - 1].isalpha():
            return False
          if i == len(token) - 1 or not token[i + 1].isalpha():
            return False
          if countHyphen == 1:
            return False
          countHyphen += 1
        if c in ['!', '.', ',']:
          if i != len(token) - 1:
            return False
      return True

    return sum(isValid(token) for token in sentence.split())