[LeetCode]709. To Lower Case

709. To Lower Case

Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

题目很简单,说的就是英文字符串,转换成小写。

Example 1:

1
2
Input: "Hello"
Output: "hello"

Example 2:

1
2
Input: "here"
Output: "here"

Example 3:

1
2
Input: "LOVELY"
Output: "lovely"

方案一

首先想到的就是遍历字符串,判断每一个字符是否是大写,如果是大写,则按照ASCII码,转换成小写后,添加到一个新的字符串里;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string toLowerCase(string str) {
string out;
for(char &i : str) {
if ((i >= 65) && (i <= 90)) {
i=i+32;
out.push_back(i);
} else {
out.push_back(i);
}
}
return out;
}
};

result

Runtime: 4 ms, faster than 100.00% of C++ online submissions for To Lower Case.

Memory Usage: 8.3 MB, less than 50.42% of C++ online submissions for To Lower Case.

结果看起来还可以,内存占用有点高,想着怎么优化一下;

方案二

string out,占用了一个新建的字符串,是不是可以在原来的字符串里面修改?try try see.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string toLowerCase(string str) {
unsigned int len = str.length();
for(unsigned i = 0; i < len; ++i) {
char ch = str[i];
if ((ch >= 65) && (ch <= 90)) {
str[i]=ch+32;
}
}
return str;
}
};

result

Runtime: 4 ms, faster than 100.00% of C++ online submissions for To Lower Case.

Memory Usage: 8 MB, less than 99.17% of C++ online submissions for To Lower Case.

内存占用降低了点,效果还可以。