Skip to content

709. To Lower Case 👎

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  string toLowerCase(string str) {
    const int diff = 'A' - 'a';

    for (char& c : str)
      if (c >= 'A' && c <= 'Z')
        c -= diff;

    return str;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public String toLowerCase(String str) {
    final int diff = 'A' - 'a';

    char[] ans = str.toCharArray();

    for (int i = 0; i < ans.length; ++i)
      if (ans[i] >= 'A' && ans[i] <= 'Z')
        ans[i] -= diff;

    return new String(ans);
  }
}
1
2
3
class Solution:
  def toLowerCase(self, str: str) -> str:
    return ''.join(chr(ord(c) + 32) if 'A' <= c <= 'Z' else c for c in str)