
问题
给定一个单词,你需要判断单词的大写使用是否正确。
我们定义,在以下情况时,单词的大写用法是正确的:
全部字母都是大写,比如”USA”。
单词中所有字母都不是大写,比如”leetcode”。
如果单词不只含有一个字母,只有首字母大写, 比如 “Google”。
否则,我们定义这个单词没有正确使用大写字母。
输入: “USA”
输出: True
输入: “FlaG”
输出: False
注意: 输入是由大写和小写拉丁字母组成的非空单词。
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.
Input: “USA”
Output: True
Input: “FlaG”
Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
示例
public class Program { public static void Main(string[] args) { var word = "isA"; var res = DetectCapitalUse(word); Console.WriteLine(res); word = "Google"; res = DetectCapitalUse2(word); Console.WriteLine(res); Console.ReadKey(); } private static bool DetectCapitalUse(string word) { //定义结果 var res = string.Empty; //大写字母用1表示,小写字母用0表示 foreach(var c in word) { if(c >= 'a' && c <= 'z') res += '0'; else res += '1'; } //去除前导0为空,表示全小写 //去除前导1为空,表示全大写 //去除后导0为1,表示首字母大写 return res.TrimStart('0') == "" || res.TrimStart('1') == "" || res.TrimEnd('0') == "1"; } private static bool DetectCapitalUse2(string word) { //直接判定 return word == word.ToLower() || word == word.ToUpper() || (word[0].ToString() == word[0].ToString().ToUpper() && word.Substring(1) == word.Substring(1).ToLower()); } }
以上给出2种算法实现,以下是这个案例的输出结果:
False True
分析:
DetectCapitalUse 的时间复杂度为 ,DetectCapitalUse2 的时间复杂度也应当为:
,因为使用了部分运行库,不能简单的认为它的时间复杂度为
。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3947。