Given a string, toggle the case of each letter: uppercase letters become lowercase and lowercase letters become uppercase. Non-alphabetic characters remain unchanged. Return the transformed string.
For example, "Hello World" becomes "hELLO wORLD". "ABC123" becomes "abc123". An empty string returns "".
Case toggling is a text transformation operation used in formatting, cryptography (ROT13 variant), and accessibility. It tests character-by-character manipulation and ASCII value arithmetic.
The solution iterates through each character. If it is uppercase (between 'A' and 'Z'), convert to lowercase by adding 32 to its ASCII value. If it is lowercase (between 'a' and 'z'), convert to uppercase by subtracting 32. Otherwise, leave it unchanged.
Edge cases include an empty string (return ""), a string with no letters (return unchanged), and Unicode characters (only standard ASCII letters are toggled).
Example Input & Output
Uppercase to lowercase
Empty string
Toggle case of each letter
Non-letters unchanged
Lowercase to uppercase
Algorithm Flow
Solution Approach
Iterate through the string and toggle each letter's case using ASCII value arithmetic.
Build a result string character by character. For uppercase letters, convert to lowercase. For lowercase letters, convert to uppercase. For all other characters, append unchanged.
Time complexity is O(n), space complexity is O(n) for the result.
Best Answers
class Solution {
public String solution(String s) {
StringBuilder sb=new StringBuilder();
for(int i=0;i<s.length();i++){char c=s.charAt(i);
if(Character.isUpperCase(c))sb.append(Character.toLowerCase(c));
else if(Character.isLowerCase(c))sb.append(Character.toUpperCase(c));
else sb.append(c);
}return sb.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
