Number of Changing Keys (LeetCode)
Problem Descriptionβ
Problem Statement | Solution Link | LeetCode Profile |
---|---|---|
Number of Changing Keys | Number of Changing Keys Solution on LeetCode | vaishu_1904 |
Problem Descriptionβ
You are given a 0-indexed string s
typed by a user. Changing a key is defined as using a key different from the last used key. For example, s = "ab"
has a change of a key while s = "bBBb"
does not have any.
Return the number of times the user had to change the key.
Note: Modifiers like shift or caps lock won't be counted in changing the key that is if a user typed the letter 'a' and then the letter 'A' then it will not be considered as a changing of key.
Example 1β
- Input:
s = "aAbBcC"
- Output:
2
- Explanation:
- From
s[0] = 'a'
tos[1] = 'A'
, there is no change of key as caps lock or shift is not counted. - From
s[1] = 'A'
tos[2] = 'b'
, there is a change of key. - From
s[2] = 'b'
tos[3] = 'B'
, there is no change of key as caps lock or shift is not counted. - From
s[3] = 'B'
tos[4] = 'c'
, there is a change of key. - From
s[4] = 'c'
tos[5] = 'C'
, there is no change of key as caps lock or shift is not counted.
- From
Example 2β
- Input:
s = "AaAaAaaA"
- Output:
0
- Explanation: There is no change of key since only the letters 'a' and 'A' are pressed which does not require change of key.
Constraintsβ
1 <= s.length <= 100
s
consists of only upper case and lower case English letters.
Approachβ
To solve this problem, we need to traverse the string and count the number of times the current character is different from the previous character when case is ignored. Here are the steps:
- Initialize a counter to keep track of the number of key changes.
- Traverse the string from the second character to the end.
- For each character, compare it with the previous character (case insensitive).
- If they are different, increment the counter.
Solution Codeβ
Pythonβ
class Solution:
def countKeyChanges(self, s: str) -> int:
count = 0
for i in range(1, len(s)):
if s[i].lower() != s[i-1].lower():
count += 1
return count
C++β
#include <string>
#include <cctype>
using namespace std;
class Solution {
public:
int countKeyChanges(string s) {
int count = 0;
for (int i = 1; i < s.length(); ++i) {
if (tolower(s[i]) != tolower(s[i-1])) {
count++;
}
}
return count;
}
};
Javaβ
class Solution {
public int countKeyChanges(String s) {
int count = 0;
for (int i = 1; i < s.length(); ++i) {
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(i-1))) {
count++;
}
}
return count;
}
}
Conclusionβ
The solutions traverse the string and count the number of times the key changes based on case-insensitive character comparison. This ensures that the problem is solved in a straightforward and efficient manner across different programming languages.