LeetCode 题解工作台

检测大写字母

我们定义,在以下情况时,单词的大写用法是正确的: 全部字母都是大写,比如 "USA" 。 所有字母都不是大写,比如 "leetcode" 。 只有首字母大写, 比如 "Google" 。 给你一个字符串 word 。如果大写用法正确,返回 true ;否则,返回 false 。 示例 1: 输入: …

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们可以统计字符串中大写字母的个数,然后根据大写字母的个数判断是否符合题目要求。 - 如果大写字母的个数为 0 或者等于字符串的长度,那么返回 `true`。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

我们定义,在以下情况时,单词的大写用法是正确的:

  • 全部字母都是大写,比如 "USA"
  • 所有字母都不是大写,比如 "leetcode"
  • 只有首字母大写, 比如 "Google"

给你一个字符串 word 。如果大写用法正确,返回 true ;否则,返回 false

 

示例 1:

输入:word = "USA"
输出:true

示例 2:

输入:word = "FlaG"
输出:false

 

提示:

  • 1 <= word.length <= 100
  • word 由小写和大写英文字母组成
lightbulb

解题思路

方法一:统计大写字母的个数

我们可以统计字符串中大写字母的个数,然后根据大写字母的个数判断是否符合题目要求。

  • 如果大写字母的个数为 0 或者等于字符串的长度,那么返回 true
  • 如果大写字母的个数为 1 并且第一个字母是大写字母,那么返回 true
  • 否则返回 false

时间复杂度 O(n)O(n),其中 nn 为字符串 word 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        cnt = sum(c.isupper() for c in word)
        return cnt == 0 or cnt == len(word) or (cnt == 1 and word[0].isupper())
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate efficiently identifies string-driven checks to validate each capitalization rule.

  • question_mark

    Candidate might miss the importance of using Python's string methods like `.upper()` and `.istitle()`.

  • question_mark

    Candidate could misinterpret the rules, for example, returning true for mixed capitalization where it's invalid.

warning

常见陷阱

外企场景
  • error

    Confusing mixed capital cases (like 'FlaG') as valid when it does not meet any of the rules.

  • error

    Overcomplicating the solution by adding unnecessary conditions or checks.

  • error

    Forgetting to handle edge cases such as very short strings like 'A' or 'a'.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check for variations in capitalization beyond the basic three rules (e.g., alternating case).

  • arrow_right_alt

    Handle words with punctuation or non-alphabetical characters (though these are out of scope for this problem).

  • arrow_right_alt

    Extend the solution to work with multiple strings or inputs in batch processing.

help

常见问题

外企场景

检测大写字母题解:String-driven solution … | LeetCode #520 简单