Skip to content

709. To Lower Case

题目

Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.

 

Example 1:

Input: s = "Hello"
Output: "hello"

Example 2:

Input: s = "here"
Output: "here"

Example 3:

Input: s = "LOVELY"
Output: "lovely"

 

Constraints:

  • 1 <= s.length <= 100
  • s consists of printable ASCII characters.
Related Topics
  • 字符串

  • 👍 259
  • 👎 0
  • 思路

    这是一道非常经典的位运算的入门题。

    • 大写字母A的 ASCII 为65
    • 小写字母 a 的 ASCII 为 97

    大写字母与小写字母之间的间距不是本能反应的间隔 26 个,而是 32

    分析原因如下:

    储存26个字母需要使用到5位(在二进制中5位可表示 0 - 24 范围内的数字) 第6位的数字可表示其为大写或小写

    故大小写切换只需要改变第6位数即可,用二进制表示 0b100000 即十进制 32

    转换公式

    • 均转换为小写字符: char | 32
    • 均转换成大写字符: char & ~32
    • 大小写互相转换: char ^ 32

    解法

    py
    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution:
        def toLowerCase(self, s: str) -> str:
            res = ''
            for i in s:
                res += chr(ord(i) | 32) if  'A' <= i <='Z' else i
            return res
            
    # leetcode submit region end(Prohibit modification and deletion)

    复杂度分析

    • 时间复杂度O(N)
    • 空间复杂度O(N), N = len(s) 因为 python 无法修改字符串的独立字符,换成 Javascript 可为 O(1)