Algorithm
Problem Name: 520. Detect Capital
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.
Example 1:
Input: word = "USA" Output: true
Example 2:
Input: word = "FlaG" Output: false
Constraints:
1 <= word.length <= 100
word
consists of lowercase and uppercase English letters.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public boolean detectCapitalUse(String word) {
boolean firstUpperCase = Character.isUpperCase(word.charAt(0));
boolean allUpperCase = false;
for (int i = 1; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
if (!firstUpperCase) {
return false;
}
if (i == 1) {
allUpperCase = true;
} else {
if (!allUpperCase) {
return false;
}
}
} else {
if (allUpperCase) {
return false;
}
}
}
return true;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const ac = "A".charCodeAt(0);
const zc = "Z".charCodeAt(0);
const detectCapitalUse = function(word) {
if (allCap(word) || noCap(word) || capHead(word)) {
return true;
}
return false;
};
function allCap(str) {
let c;
for (let i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
if (c < ac || c > zc) {
return false;
}
}
return true;
}
function noCap(str) {
let c;
for (let i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
if (c >= ac && c < = zc) {
return false;
}
}
return true;
}
function capHead(str) {
let c;
let first;
for (let i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
if (i === 0) {
first = c;
} else if (c >= ac && c < = zc) {
return false;
}
}
if (first >= ac && first <= zc) {
return true;
} else {
return false;
}
}
console.log(detectCapitalUse("ffffffffffffffffffffF"));
console.log(detectCapitalUse("Leetcode"));
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def detectCapitalUse(self, word):
return word[0].isupper() and word[1:].islower() or word.isupper() or word.islower()
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0520_DetectCapital
{
public bool DetectCapitalUse(string word)
{
var upper = 0;
foreach (var ch in word)
if (ch >= 'A' && ch < = 'Z')
upper++;
if (upper == 1 && word[0] <= 'Z') return true;
return upper == 0 || upper == word.Length;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output