Sunday, May 14, 2017

Number of Segments in a String


Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:

Input: "Hello, my name is John"
Output: 5

Link to GitHub :Code


Solution

  • Take integer variable to keep the count of consecutive spaces
  • Loop through the string and check if 2 consecutive characters are spaces.If yes increment the counter
  • We also need consider the first character at 0 position
Time complexity:  O(n)
Space complexity: O(1)
package Algorithms.Strings;

public class NoSegmentsInString {
 
 public static int get(String s)
 {
   int res=0;
   for (int i=0;i<s.length();i++)
   {
    //This condition, we are looking for two spaces and 0 position
    if(s.charAt(i)!=' ' && (i==0 || s.charAt(i-1)==' '))
    {
     res++;
    }
   }
   return res;
 }

}

No comments:

Post a Comment