string
]
Leetcode 0520. Detect Capital
https://leetcode.com/problems/detect-capital
We can solve this problem in oneline, if we use python functionality: functions isupper()
islower()
and istitle()
. I think the first two ones are pretty classical and a lot of people aware of them (if not, it is very easy to write this function, just check if symbol is between a
and z
for islower()
and from A
to Z
for isupper()
). Howerer the third one is a bit cheating, so I decided not to use it.
So, we can have three cases. Let us evaluate number of capital letters first:
- If number of capital letters is equal to
0
, then we returnTrue
. - If number of capital letters is equal to
n
- number of all letters, we also returnTrue
. - If number of capital letters is equal to
1
and first letter is capital, we returnTrue
. - If none of
3
conditions above fulfilled, we returnFalse
.
Complexity: time complexity is O(n)
, because we traverse our string once. Space complexity is O(1)
, because we have only couple of additional constants.
class Solution:
def detectCapitalUse(self, word):
Num_cap, n = 0, len(word)
for letter in word:
Num_cap += letter.isupper()
if Num_cap == 0 or Num_cap == n or Num_cap == 1 and word[0].isupper():
return True
return False
If you like the solution, you can upvote it on leetcode discussion section: Problem 0520