Leetcode 365 (2023)

Akinmegha Temitope SamuelAkinmegha Temitope Samuel

Day 2: 520. Detect Capital Using JavaScript

Hi there, we continue with our daily leetcode DSA questions,

And now to Day 2 Question on Detect capital using JavaScript

We define the usage of capitals in a word to be right when one of the following cases holds:

  • All letters in this word are capitals, like "USA".

  • All letters in this word are not capitals, like "leetcode".

  • Only the first letter in this word is capital, like "Google".

Given a string word, return true if the usage of capitals in it is right.

Examples of test cases are given

Input: word = "USA"
Output: true
Input: word = "FlaG"
Output: false
  • 1 <= word.length <= 100

  • word consists of lowercase and uppercase English letters.

    Approach I:

    The method of regular expression(Regex) can be implemented to show if a word has all capital letters, small letters and if the first letter of the word in capital letters.

    Regex : Regular expressions are patterns used to match character combinations in strings. The regular pattern is defined from the question.The JavaScript code is shown simplify the cases of all capital letters, all small letters and the first word being capital letter

      /**
       * @param {string} word
       * @return {boolean}
       */
      let detectCapitalUse = (word) => {
      //returns all capital letters, small letter or the first letter being capital letter
          return /^[A-Z]+$|^[a-z]+$|^[A-Z][a-z]+$/.test(word);
      };
    

    The function above returns a boolean indicating if the capitalization in the given word holds true. Just like that, you can determine the boolean value from the Regex format that applies to different test cases.

  • Approach II:

  • This makes use of the substring() function in JavaScript which extracts part of a string and outputs a new string, how does this string extract apply to the question?

  • See below

var detectCapitalUse = function (word) {
    return (word.substr(1).toLowerCase() == word.substr(1) || word.toUpperCase() == word)
};

Thank you for reading, I'll see you on Day 3.