Skip to content

Latest commit

 

History

History
166 lines (126 loc) · 2.86 KB

File metadata and controls

166 lines (126 loc) · 2.86 KB

English Version

题目描述

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

 

示例 1:

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

示例 2:

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

示例 3:

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

 

提示:

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

解法

遍历字符串,遇到大写的字符,转小写。

Python3

class Solution:
    def toLowerCase(self, s: str) -> str:
        return ''.join(
            [chr(ord(c) | 32) if ord('A') <= ord(c) <= ord('Z') else c for c in s]
        )

Java

class Solution {
    public String toLowerCase(String s) {
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; ++i) {
            if (chars[i] >= 'A' && chars[i] <= 'Z') {
                chars[i] |= 32;
            }
        }
        return new String(chars);
    }
}

C++

class Solution {
public:
    string toLowerCase(string s) {
        for (char& c : s)
            if (c >= 'A' && c <= 'Z')
                c |= 32;
        return s;
    }
};

Go

func toLowerCase(s string) string {
	sb := &strings.Builder{}
	sb.Grow(len(s))
	for _, c := range s {
		if c >= 'A' && c <= 'Z' {
			c |= 32
		}
		sb.WriteRune(c)
	}
	return sb.String()
}

TypeScript

function toLowerCase(s: string): string {
    return s.toLowerCase();
}
function toLowerCase(s: string): string {
    return [...s].map(c => String.fromCharCode(c.charCodeAt(0) | 32)).join('');
}

Rust

impl Solution {
    pub fn to_lower_case(s: String) -> String {
        s.to_ascii_lowercase()
    }
}
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()
    }
}

C

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;
}

...