The title

Give you a string s, convert the uppercase letters in the string to the same lowercase letters, and return the new string.

Example 1:

Input: s = "Hello" Output: "Hello"Copy the code

Example 2:

Input: s = "here" Output: "here"Copy the code

Example 3:

Input: s = "LOVELY" Output: "LOVELY"Copy the code

Tip:

1 <= S. length <= 100 s consists of printable characters in the ASCII character setCopy the code

Answer key

Solution one: use Swift language features

Time complexity: O(n)

Spatially complex: O(n)

Code:

func toLowerCase(_ s: String) -> String {
        return s.lowercased()
}
Copy the code

Submission Results:

Solution 2: Write the upper and lower case characters into the dictionary and iterate the query for replacement

Time complexity: O(n)

Spatially complex: O(n)

Code:

func toLowerCase(_ s: String) -> String {
        var result: String = s
        for item in s {
            result = result.replacingOccurrences(of: String(item), with: lower(String(item)))
        }
        return s.lowercased()
    }
    private func lower(_ s: String) -> String {
        let hash = ["A":"a", "B":"b", "C":"c", "D":"d", "E":"e", "F":"f",
                    "G":"g", "H":"h", "I":"i", "J":"j", "K":"k", "L":"l",
                    "M":"m", "N":"n", "O":"o", "P":"p", "Q":"q", "R":"r",
                    "S":"s", "T":"t", "U":"u", "V":"v", "W":"w", "X":"x",
                    "Y":"y", "Z":"z"]
        
        if let s1 = hash[s] {
            return s1
        }
        return ""
    }
Copy the code

Submission Results:

Solution 3: use ASCII code

The ASCII code range of uppercase a-z is [65,90]

The ASCII code range for lowercase a-z is [97,122].

Time complexity: O(n)

Spatially complex: O(1)

Code:

func toLowerCase(_ s: String) -> String {
        var result: String = ""
        for item in s.unicodeScalars {
            if item.value >= 65, item.value <= 90  {
                result += String(UnicodeScalar(item.value + 32)!)
            }else {
                result += String(UnicodeScalar(item.value)!)
            }
        }
        return s.lowercased()
    }
Copy the code

Submission Results:

LeetCode link