Skip to content

Latest commit

 

History

History
85 lines (59 loc) · 1.83 KB

File metadata and controls

85 lines (59 loc) · 1.83 KB

English Version

题目描述

实现函数 ToLowerCase(),该函数接收一个字符串参数 str,并将该字符串中的大写字母转换成小写字母,之后返回新的字符串。

 

示例 1:

输入: "Hello"
输出: "hello"

示例 2:

输入: "here"
输出: "here"

示例 3:

输入: "LOVELY"
输出: "lovely"

解法

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

Python3

class Solution:
    def toLowerCase(self, str: str) -> str:
        if not str:
            return str
        n = len(str)
        res = []
        for i in range(n):
            c = ord(str[i])
            if c >= 65 and c <= 90:
               c += 32
            res.append(chr(c))
        return ''.join(res)

Java

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

...