CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
Word Count
string
# Word Count ## Difficulty Easy ## Tags `string` ## Problem Statement Implement a simplified version of the Unix `wc` (word count) tool. Count the number of words in a given string. A "word" is defined as a maximal sequence of non-whitespace characters. ## Constraints - Whitespace includes spaces, tabs (`\t`), and newlines (`\n`). - Handle multiple consecutive whitespace characters correctly. - 0 ≤ text.length ≤ 10⁴ ## Signatures ### Python ```python def word_count(text: str) -> int: pass ``` ### Java ```java public class Solution { public int word_count(String text) { return null; } } ``` ### Csharp ```csharp public class Solution { public int word_count(string text) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: int word_count(string text) { } }; ``` ### C ```c int word_count(char* text) { } ``` ### Ruby ```ruby def word_count(text) end ``` ### Perl ```perl sub word_count { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def word_count(text: String): Int = { } } ``` ### Haskell ```haskell word_count :: ... -> ... word_count args = undefined ``` ### Clojure ```clojure (defn word_count [text] ) ``` ### Scheme ```scheme (define (word_count text) ) ``` ## Examples ### Example 1 **Input:** ``` text = "Hello world" ``` **Output:** ``` 2 ``` ### Example 2 **Input:** ``` text = "Hello world\nfrom Python" ``` **Output:** ``` 4 ``` **Explanation:** Words are "Hello", "world", "from", "Python". Multiple spaces and newlines separate them. ### Example 3 **Input:** ``` text = " " ``` **Output:** ``` 0 ``` **Explanation:** Only whitespace, no words. ### Example 4 **Input:** ``` text = "" ``` **Output:** ``` 0 ``` ### Example 5 **Input:** ``` text = " leading and trailing " ``` **Output:** ``` 3 ``` ## Hints 1. **Simple approach**: Use `split()` which handles multiple spaces. Return length of resulting list. 2. **Manual approach**: Iterate character by character, track whether you're inside a word using a boolean flag. 3. Increment word count when transitioning from whitespace to non-whitespace.
Login required
Please log in to view the solution editor and submit code.
Login
Register