arcbjorn

thoughtbook

RSS Feed

Saturday, December 24, 2022

Detect capital

Leetcode 520 problem.

A function to determine if the usage of capitals in a word is correct.

Go

  • Time complexity: O(n)O(n) - n is a length of a string
  • Auxiliary space: O(1)O(1) - constant amount of space
import "strings"

func detectCapitalUse(word string) bool {
    // all lowercase
    if (strings.ToLower(word) == word) {
        return true
    }

    // all uppercase
    if (strings.ToUpper(word) == word) {
        return true
    }

    // from second letter lowercase
    if (strings.ToLower(word[1:]) == word[1:]) {
        return true
    }

    return false
}
Creative Commons Licence