LeetCode之路:520. Detect Capital

来源:互联网 发布:高斯面膜 知乎 编辑:程序博客网 时间:2024/05/16 10:28

一、引言

这道题有关于处理字符的大小写问题,对于熟悉字符的大小写处理函数非常有帮助。

这里粘出题目信息:

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 if it has more than one letter, like “Google”.
Otherwise, we define that this word doesn’t use capitals in a right way.

这道题看上去应该比较简单,重点是我们如何快速的分析题意,以最简洁的方式解出题目来。

二、看看我的分析

按照题目意思,合法的大写使用情况有几种呢:

合法情况 单词第 1 位 单词第 1 位之外 全部大写 U U 全部小写 L L 第 1 位大写其后全部小写 U L

注:这里用 U 表示大写,用 L 表示小写

这里可以看到,有三种情况可以判定使用合法,那么在代码中我们就要判断三种情况吗?

当然不是,这样肯定可以做出来,但是太过于复杂,不如我们换个角度思考,我们来考虑不合法的情况:

非法情况 单词第 1 位 单词第 1 位之外 第 1 位小写,其后位置有大写字母 L 存在 U 字母 第 1 位大写,其后位置有大写字母也有小写字母 U 存在 U 和 L 字母

那么,我们需要判断的情况,就由 3 种简化成了 2 中。

根据上述分析,代码如下:

// my solution2, runtime = 9 msclass Solution2 {public:    bool detectCapitalUse(string word) {        if (word.size() == 1) return true;        if (islower(word[0])) {            for (auto i : word)                if (isupper(i)) return false;            return true;        } else {            bool hasUpper = false;            bool hasLower = false;            for (size_t i = 1; i < word.size(); ++i) {                if (islower(word[i])) hasLower = true;                else hasUpper = true;            }            if (hasUpper && hasLower) return false;            else return true;        }    }};

那么,还有没有其他的思路呢?

三、看看别人的三行代码

当然有其他的思路了。

上述方法中,我一直在考虑如何在遍历中判断大小写,并且直接返回结果。

这里有一种方法,就是记录单词中的大写字母的个数,与上述分析一样的判断,判断是否合法。

直接看代码直观些:

// other's solution , runtime = 9 msclass Solution3 {public:    bool detectCapitalUse(string word) {        int count = 0;        for (auto i : word) if (isupper(i)) ++count;        return !count || count == word.size() || isupper(word[0]) && count == 1;    }};

其实呢,判断逻辑都是差不多的,只是判断根据换成了大写字母的个数与单词总数的比较,尽管 runtime 差不多,但是很明显这种方法更加的直观、简洁。

追求代码的简洁是我的爱好,To be Continue!

1 0