跳转至

709. 转换成小写字母

题目描述

给你一个字符串 s ,将该字符串中的大写字母转换成相同的小写字母,返回新的字符串。

 

示例 1:

输入:s = "Hello"
输出:"hello"

示例 2:

输入:s = "here"
输出:"here"

示例 3:

输入:s = "LOVELY"
输出:"lovely"

 

提示:

  • 1 <= s.length <= 100
  • s 由 ASCII 字符集中的可打印字符组成

解法

方法一:模拟

我们可以遍历字符串,对于每个大写字母,将其转换为小写字母。最后返回转换后的字符串即可。

时间复杂度 \(O(n)\),其中 \(n\) 为字符串的长度。忽略答案的空间消耗,空间复杂度 \(O(1)\)

1
2
3
class Solution:
    def toLowerCase(self, s: str) -> str:
        return "".join([chr(ord(c) | 32) if c.isupper() else c for c in s])
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public String toLowerCase(String s) {
        char[] cs = s.toCharArray();
        for (int i = 0; i < cs.length; ++i) {
            if (cs[i] >= 'A' && cs[i] <= 'Z') {
                cs[i] |= 32;
            }
        }
        return String.valueOf(cs);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
public:
    string toLowerCase(string s) {
        for (char& c : s) {
            if (c >= 'A' && c <= 'Z') {
                c |= 32;
            }
        }
        return s;
    }
};
1
2
3
4
5
6
7
8
9
func toLowerCase(s string) string {
    cs := []byte(s)
    for i, c := range cs {
        if c >= 'A' && c <= 'Z' {
            cs[i] |= 32
        }
    }
    return string(cs)
}
1
2
3
function toLowerCase(s: string): string {
    return s.toLowerCase();
}
1
2
3
4
5
impl Solution {
    pub fn to_lower_case(s: String) -> String {
        s.to_ascii_lowercase()
    }
}
1
2
3
4
5
6
7
8
9
char* toLowerCase(char* s) {
    int n = strlen(s);
    for (int i = 0; i < n; i++) {
        if (s[i] >= 'A' && s[i] <= 'Z') {
            s[i] |= 32;
        }
    }
    return s;
}

方法二

1
2
3
function toLowerCase(s: string): string {
    return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join('');
}
1
2
3
4
5
6
7
8
impl Solution {
    pub fn to_lower_case(s: String) -> String {
        s.as_bytes()
            .iter()
            .map(|&c| char::from(if c >= b'A' && c <= b'Z' { c | 32 } else { c }))
            .collect()
    }
}

评论

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy