समस्या
A word is a run of non-space characters. Count the words in text; there may be extra spaces at the start, end or between words.
Implement count_words(text).
Input
text: The text to count.
Output
Return the number of words.
सीमाएँ
0 ≤ length ≤ 10,000
उदाहरण
इनपुट:
text = "Learn to code today"
अपेक्षित आउटपुट:
expected = 4
इनपुट:
std::string text = "Learn to code today";
अपेक्षित आउटपुट:
long long expected = 4;
इनपुट:
string text = "Learn to code today";
अपेक्षित आउटपुट:
long expected = 4;
व्याख्या
Four words separated by spaces: 4.
इनपुट:
text = " "
अपेक्षित आउटपुट:
expected = 0
इनपुट:
std::string text = " ";
अपेक्षित आउटपुट:
long long expected = 0;
इनपुट:
string text = " ";
अपेक्षित आउटपुट:
long expected = 0;
व्याख्या
Only spaces, so there are no words: 0.
कैसे हल करें
पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।
संकेत 1
A word is any consecutive stretch of non-space characters.
संकेत 2
Scan through the text and count transitions from spaces into letters.
संकेत 3
Be careful with leading, trailing, and repeated spaces so you do not count empty runs.
अपेक्षित जटिलता
O(n) time, O(1) extra space
संदर्भ
यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।