Problem
Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
Solution
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 |
// Author: Huahua // Running time: 0 ms class Solution { public: string toLowerCase(string str) { for (char &c : str) if (c >= 'A' && c <= 'Z') c = c - 'A' + 'a'; return str; } }; |
Java
1 2 3 4 5 6 7 8 9 |
// Author: Huahua, 1 ms class Solution { public String toLowerCase(String str) { char[] s = str.toCharArray(); for (int i = 0; i < s.length; ++i) if (s[i] >= 'A' && s[i] <= 'Z') s[i] = (char)(s[i] - 'A' + 'a'); return new String(s); } } |
Python3
1 2 3 4 5 6 7 8 9 10 |
# Author: Huahua, 40 ms class Solution: def toLowerCase(self, str): ans = '' for c in str: if c >= 'A' and c <= 'Z': ans += chr(ord(c) + 32) else: ans += c return ans |
Python3 1-linear
1 2 3 4 |
# Author: Huahua, 68 ms class Solution: def toLowerCase(self, str): return ''.join(chr(ord(c) + 32) if c >= 'A' and c <= 'Z' else c for c in str) |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment