Write a function to count the words in a string. (without using any in-built split functions. The only delimiter is space).
My Thought Process :
Right of the bat , Start counting space characters. But realized that this would fail if all the characters are spaces. Alright, rethink. Make $word_count =0; Start reading characters, if space, skip till next character not a space. Increment the $word_count. But this was also flawed (for input " some word "). So finally after a 2nd rethink. Here's my answer :
public static int word_count(String s1){
// Function to calculate number of words in a string
int count = 0;
if(s1 == null)
return count;
int i= 0 ;
while(i < s1.length()){
while(i <s1.length() && s1.charAt(i) == ' ')
i++;
if(i == s1.length())
break;
else
{
count++;
while(i<s1.length() && s1.charAt(i) != ' ')
i++;
}
}
return count;
}
Complexity :Time : O(n) : n being number of characters.
Space: O(1) : Just one variable space needed.
No comments:
Post a Comment