Blogs Hub

Detect Capital - MiniTV

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);
        }
    }
}