Leetcode

Number of Valid Words in a Sentence

  • Time:O(n)
  • Space:O(n)

C++

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;
  }
};

JAVA

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;
  }
}

Python

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())