![]() |
VOOZH | about |
Given a string s consisting of lowercase English alphabets, spaces, tab characters (\t), and newline characters (\n), count the total number of words present in the string. A word is defined as a continuous sequence of lowercase English letters, while spaces, tabs, and newline characters act as separators between words.
Examples:
Input: s = "abc def"
Output: 2
Explanation: There is a space at 4th position which works as a separator between "abc" and "def".Input: s = "a\nyo\t"
Output: 2
Explanation: There are two words in the string: "a" and "yo". The characters \n and \t act as separators, splitting the string into words.Input: s = "a\t\tb aa"
Output: 3
Explanation: There are three words in the string: "a", "b", and "aa". The tab characters (\t\t) and space act as separators between the words.
Table of Content
The idea is to traverse the string and detect the starting point of every word. We use a boolean variable inWord to track whether we are currently inside a word or not.
Whenever a lowercase letter appears after a separator like space (' '), newline ('\n'), or tab ('\t'), it means a new word has started, so we increment the count.
Consider the string: s = "a\nyo\n"
Initially, count = 0 and inWord = false, and start traversing the string character by character.
After traversing the complete string, the total number of words is 2.
2
The idea is to use built-in string splitting methods that automatically separate words using whitespace characters like spaces, tabs ('\t'), and newlines ('\n').
After splitting the string, each extracted part represents a word. So, the total number of extracted parts gives the required answer.
2