Site icon Study Algorithms

[Hackerrank] – Camel Case Solution

Let us try to understand this problem statement first. We have a string in camel case and we have to find the total number of words in this string. A camel case representation is a special representation of string where the first word starts with a small letter, and all the subsequent words start with a capital letter.

Let us look at some sample test cases:

Input: oneTwoThree
Output: 3
Explanation:
We have 3 words
one, two, and three.

Input: jackAndJillWentUpTheHill
Output: 7
Explanation:
We have a total of 7 words
jack, and, jill, went, up, the, hill

Fig: Sample test cases

Terminology:

In the English language we separate each word by a blank space, but when it comes to programming we want to save as much space as possible. This problem introduces you to a new concept of string representation known as camel case. One must also know about a few more string representations:

Fig: Different string representations

Each of these string representations is used in different programming languages as per the conventions and best practices. They help to make your code easy to read and understand.

Solution:

The problem has a very straight forward solution. You do not need any special data structures.

Fig: Number of words in camel case representation

Code:

  public int camelcase(String s) {
    int numberOfWords = 0;

    for (int i = 0; i < s.length(); i++) {
      // Get the character
      char c = s.charAt(i);

      // Check if the character is a capital letter
      if (c >= 'A' && c <= 'Z') {
        // This is a start of new word
        numberOfWords++;
      }
    }

    // Since the first word starts with a small letter
    numberOfWords = numberOfWords + 1;

    return numberOfWords;
  }
Code language: Java (java)

Time Complexity: O(n)
Space Complexity: O(1)

You can also find the code and test cases on GitHub.

Video Explanation:

Exit mobile version