LeetCode 2268: Minimum Number of Keypresses
Problem Description
Explanation:
The problem asks us to find the minimum number of keypresses required to type a given string. We are allowed to use shift key to toggle between lowercase and uppercase characters.
To solve this problem, we can iterate through the characters of the input string and calculate the minimum number of keypresses needed to type each character. We can keep track of the current case (lowercase or uppercase) and switch it if needed using the shift key.
Algorithm:
- Initialize a variable
keyPresses
to 0 to keep track of the total keypresses. - Initialize a variable
upperCase
to false to keep track of the current case. - Iterate through each character in the input string:
- If the character is already in the correct case (based on the current case), add the keypress to type that character.
- If the character needs to be toggled to the other case, add the keypress for the shift key and then add the keypress to type the character.
- Update the current case based on the character's case.
- Return the total keypresses.
Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(1).
:
Solutions
class Solution {
public int minKeyPresses(String s) {
int keyPresses = 0;
boolean upperCase = false;
for (char c : s.toCharArray()) {
if (upperCase && Character.isLowerCase(c)) {
keyPresses += 2; // Press shift key and type the character
} else if (!upperCase && Character.isUpperCase(c)) {
keyPresses += 2; // Press shift key and type the character
upperCase = true;
}
keyPresses++; // Type the character
}
return keyPresses;
}
}
Loading editor...