Detect Capital
💻 coding

Detect Capital

2 min read 306 words
2 min read
ShareWhatsAppPost on X
  • 1The correct usage of capitals in a word can be defined by three specific cases.
  • 2A word is valid if all letters are uppercase, all are lowercase, or only the first letter is uppercase.
  • 3The provided solution has a time complexity of O(n) and space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The correct usage of capitals in a word can be defined by three specific cases."

Detect Capital

Given a word, you need to judge whether the usage of capitals in it is right or not.

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".

Otherwise, we define that this word doesn't use capitals in a right way.

Example 1:

Input: "USA"

Output: True

Example 2:

Input: "FlaG"

Output: False

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

Accepted

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 public class DetectCapitalUseSoln
 {
 public bool DetectCapitalUse(string word)
 {
 var lower = 0;
 var upper = 0;
 for (int i = 0; i < word.Length; i++)
 {
 if (IsUpper(word[i]))
 {
 upper++;
 }
 else
 {
 lower++;
 }
 }

 if (upper == 1 && IsUpper(word[0]))
 {
 return true;
 }

 return lower == 0 || upper == 0;
 }

 private bool IsUpper(char v)
 {
 if (v >= 65 && v <= 90)
 return true;
 return false;
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Test Case:

using LeetCode.AskGif.Easy.String;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodingUnitTest.Easy.String
{
 [TestClass]
 public class DetectCapitalUseSolnTests
 {
 [TestMethod]
 public void DetectCapitalUseSoln_First()
 {
 var a = "USA"; 
 var output = true;
 var res = new DetectCapitalUseSoln().DetectCapitalUse(a);

 Assert.AreEqual(res, output);
 }

 [TestMethod]
 public void DetectCapitalUseSoln_Second()
 {
 var a = "FlaG";
 var output = false;
 var res = new DetectCapitalUseSoln().DetectCapitalUse(a);

 Assert.AreEqual(res, output);
 }

 [TestMethod]
 public void DetectCapitalUseSoln_Third()
 {
 var a = "leetcode";
 var output = true;
 var res = new DetectCapitalUseSoln().DetectCapitalUse(a);

 Assert.AreEqual(res, output);
 }

 [TestMethod]
 public void DetectCapitalUseSoln_Fourth()
 {
 var a = "Google";
 var output = true;
 var res = new DetectCapitalUseSoln().DetectCapitalUse(a);

 Assert.AreEqual(res, output);
 }
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 15 May 2020 · 2 min read · 306 words

Part of AskGif Blog · coding

You might also like