Skip to content

Latest commit

 

History

History
129 lines (101 loc) · 2.34 KB

File metadata and controls

129 lines (101 loc) · 2.34 KB

中文文档

Description

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.

Solutions

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()
}

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 {
        String::from_utf8(
            s.as_bytes()
                .iter()
                .map(|&c| c + if c >= b'A' && c <= b'Z' { 32 } else { 0 })
                .collect(),
        )
        .unwrap()
    }
}

...