Count Words

Easy~10 min

Given a string s, return the number of words in the string.

A word is defined as a contiguous sequence of non-space characters. The string may contain leading spaces, trailing spaces, and multiple spaces between words.

Examples

Example 1
Input: s = "Hello World"
Output: 2
Explanation: There are two words: "Hello" and "World".
Example 2
Input: s = " fly me to the moon "
Output: 5
Explanation: There are five words: "fly", "me", "to", "the", "moon". Leading, trailing, and extra spaces are ignored.
Example 3
Input: s = "onlyoneword"
Output: 1
Explanation: The entire string is a single word.

Constraints

  • 0 <= s.length <= 10^5
  • s consists of English letters and spaces.
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run