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.
这道题看上去应该比较简单,重点是我们如何快速的分析题意,以最简洁的方式解出题目来。
二、看看我的分析
按照题目意思,合法的大写使用情况有几种呢:
注:这里用 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!
- LeetCode之路:520. Detect Capital
- LeetCode之Detect Capital
- 【Leetcode】520. Detect Capital
- LeetCode 520. Detect Capital
- LeetCode 520. Detect Capital
- LeetCode-520. Detect Capital
- leetcode 520. Detect Capital
- leetcode 520. Detect Capital
- [leetcode] 520. Detect Capital
- [LeetCode]520. Detect Capital
- LeetCode | 520. Detect Capital
- 【LeetCode】520. Detect Capital
- LeetCode 520. Detect Capital
- leetcode 520. Detect Capital
- LeetCode 520. Detect Capital
- [leetcode]: 520. Detect Capital
- leetcode 520. Detect Capital
- LeetCode:520. Detect Capital
- Android 隐藏虚拟按键及状态栏
- java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver错误在eclipse中的解决方法
- 统计 sqlServer grouping with Rollup
- Android之路的点点滴滴(补发2017.04.05-2017.04.17这一时间段之一【跑马灯】)
- SSL会话劫持
- LeetCode之路:520. Detect Capital
- 单链表题集
- 利用qsort库函数实现快速排序
- idea spark远程调试
- 使用PowerDesigner15创建MySQL数据库表结构设计
- java内外部比较器(Comparator、Comparable)使用场景与详解
- BLE 配对后通信其中一方LTK丢失情况
- header("Content-type:text/html;charset=utf-8");
- SVG实现攻击效果