current position:Home>leetcode 2047. Number of Valid Words in a Sentence(python)

leetcode 2047. Number of Valid Words in a Sentence(python)

2022-01-31 08:27:10 Wang Daya

「 This is my participation 11 The fourth of the yuegengwen challenge 10 God , Check out the activity details :2021 One last more challenge

describe

A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.

A token is a valid word if all three of the following are true:

  • It only contains lowercase letters, hyphens, and/or punctuation (no digits).
  • There is at most one hyphen '-'. If present, it must be surrounded by lowercase characters ("a-b" is valid, but "-ab" and "ab-" are not valid).
  • There is at most one punctuation mark. If present, it must be at the end of the token ("ab,", "cd!", and "." are valid, but "a!b" and "c.," are not valid).

Examples of valid words include "a-b.", "afad", "ba-c", "a!", and "!".

Given a string sentence, return the number of valid words in sentence.

Example 1:

Input: sentence = "cat and  dog"
Output: 3
Explanation: The valid words in the sentence are "cat", "and", and "dog".
 Copy code 

Example 2:

Input: sentence = "!this  1-s b8d!"
Output: 0
Explanation: There are no valid words in the sentence.
"!this" is invalid because it starts with a punctuation mark.
"1-s" and "b8d" are invalid because they contain digits.
 Copy code 

Example 3:

Input: sentence = "alice and  bob are playing stone-game10"
Output: 5
Explanation: The valid words in the sentence are "alice", "and", "bob", "are", and "playing".
"stone-game10" is invalid because it contains digits.
 Copy code 

Example 4:

Input: sentence = "he bought 2 pencils, 3 erasers, and 1  pencil-sharpener."
Output: 6
Explanation: The valid words in the sentence are "he", "bought", "pencils,", "erasers,", "and", and "pencil-sharpener.".
 Copy code 

Note:

1 <= sentence.length <= 1000
sentence only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','.
There will be at least 1 token.
 Copy code 

analysis

According to the meaning , Give a string sentence It's made up of lowercase letters ('a' To 'z')、 Numbers ('0' To '9')、 A hyphen ('-')、 Punctuation ('!'、'.' and ',') Composition and space (' ') form . Each sentence can be divided into multiple... By dividing it into one or more spaces token .

If all three of the following conditions are true True ,token For effective :

  • It contains only lowercase letters 、 A hyphen , There may also be punctuation marks ( No numbers ).
  • There is at most one hyphen “-”. If there is , It must be surrounded by lowercase characters (“a-b” It works , but “-ab” and “ab-” Invalid ).
  • At most one punctuation mark . If there is , It must be at the end of the tag (“ab,”、“cd!” and “.” It works , but “a!b” and “c.,” Invalid ).

Examples of valid words include “a-b.”、“afad”、“ba-c”、“a!” and “!”. Given a string sentence , Returns the number of valid words in a sentence .

In fact, the topics are more complicated , But the solution is simple , Just judge the three requirements in the question :

  • take sentence Divided into multiple token
  • Through each token , If it contains numbers, go to the next token The judgment of the , If it contains hyphens - More than one or not in the middle of the letter to proceed directly to the next token The judgment of the , If there is more than one punctuation point or it is not at the end, proceed to the next token The judgment of the , Otherwise, the counter is incremented by one
  • The counter result is returned after traversal

answer

class Solution(object):
    def countValidWords(self, sentence):
        """
        :type sentence: str
        :rtype: int
        """
        result = 0
        tokens = sentence.split()
        for token in tokens:
            if re.search(r'\d', token):
                continue
            if token.count('-')>1 or ('-' in token and not re.search(r'[a-z]-[a-z]', token)):
                continue
            count = token.count('!') + token.count('.') + token.count(',') 
            if count > 1:
                continue
            if count == 1:
                if token[-1] not in ['!', '.' , ',']:
                    continue
            result += 1
        return result
            
                
            
        	      
		
 Copy code 

Running results

Runtime: 40 ms, faster than 75.10% of Python online submissions for Number of Valid Words in a Sentence.
Memory Usage: 13.6 MB, less than 72.65% of Python online submissions for Number of Valid Words in a Sentence.
 Copy code 

Original link :leetcode.com/problems/nu…

Your support is my greatest motivation

copyright notice
author[Wang Daya],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201310827087962.html

Random recommended