Skip to content

Commit f605ce1

Browse files
committed
August - Day 1
1 parent 8436b61 commit f605ce1

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package com.leetcode.scala.monthly2020.august
2+
3+
/*
4+
* Given a word, you need to judge whether the usage of capitals in it is right or not.
5+
* We define the usage of capitals in a word to be right when one of the following cases holds:
6+
* All letters in this word are capitals, like "USA".
7+
* All letters in this word are not capitals, like "leetcode".
8+
* Only the first letter in this word is capital, like "Google".
9+
* Otherwise, we define that this word doesn't use capitals in a right way.
10+
* */
11+
12+
/*
13+
* Input: "USA"
14+
Output: True
15+
*
16+
* Input: "FlaG"
17+
Output: False
18+
*
19+
* */
20+
21+
/*
22+
* Approach: Iterative Force/Regex
23+
*
24+
* 1. First We will check if the first letter of string is capital or not.
25+
* 2. We have to iterate through each character and count the number of lower case and upper case character.
26+
* 3. If number of upper case == length of string or number of lower case == length of string we have to return true.
27+
* 4. If upper count is 1 and first letter of the string is upper case and lowercount + 1 == length of string we have to return true.
28+
* 5. For all other cases we will return false.
29+
*
30+
* */
31+
32+
33+
object DetectCapital {
34+
def main(args: Array[String]): Unit = {
35+
var testCases = Array("USA", "leetcode", "UsA", "USa", "usA", "Happy")
36+
val expectedResults = Array(true, true, false, false, false, true)
37+
val actualResult = testCases.map(a => detectCapitalUse(a))
38+
println(s"Result: ${actualResult.mkString(" ")}, ${actualResult.sameElements(expectedResults)}")
39+
}
40+
41+
def detectCapitalUse(word: String): Boolean = {
42+
var upperCount = 0
43+
var lowerCount = 0
44+
val length = word.length
45+
val firstElem = word.head >= 65 & word.head <= 90
46+
word.foreach(a => {
47+
if (a >= 97 & a <= 122) lowerCount += 1
48+
if (a >= 65 & a <= 90) upperCount += 1
49+
})
50+
if (length == upperCount) return true
51+
if (length == lowerCount) return true
52+
if (upperCount == 1 && firstElem && length == (1 + lowerCount)) {
53+
return true
54+
}
55+
return false
56+
}
57+
58+
def detectCapitalUseRegex(word: String): Boolean = {
59+
word.matches("[A-Z]*|.[a-z]*")
60+
}
61+
}

0 commit comments

Comments
 (0)