C# - 1 liner


  • 2

    Either all are capital or from 2nd char on wards must be lower case.

        public bool DetectCapitalUse(string word) 
        {
            return word.All(c => c - 'A' < 26) || word.Substring(1).All(c => c - 'a' >= 0);
        }
    

    for comparison here is the non Linq version, not quite as concise!

        public bool DetectCapitalUse(string word) 
        {
            if (word.Length < 2) return true;
            bool firstIsCapital = word[0] - 'A' < 26;
            bool secondIsCapital = word[1] - 'A' < 26;
            if (!firstIsCapital && secondIsCapital) return false;
            for (int i = 2; i < word.Length; i++)
            {
                bool isCapital = word[i] - 'A' < 26;
                if ((secondIsCapital && !isCapital) || (!secondIsCapital && isCapital)) return false;
            }
            return true;
        }
    

  • 0
    J

    @jdrogin

    public bool DetectCapitalUse(string word) {
        return word.All(char.IsUpper) || word.Skip(1).All(char.IsLower);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.