Number of Changing Keys
Problem
You are given a string s typed by a user. Count the number of times the user had to change the key used. Changing a key is using a key different from the last used key; modifiers like shift and caps lock do not count, so case is ignored ('a' and 'A' are the same key).
s = "aAbBcC"2def count_key_changes(s):
changes = 0
for i in range(1, len(s)):
if s[i].lower() != s[i - 1].lower():
changes += 1
return changes
function countKeyChanges(s) {
let changes = 0;
for (let i = 1; i < s.length; i++) {
if (s[i].toLowerCase() !== s[i - 1].toLowerCase()) {
changes++;
}
}
return changes;
}
class Solution {
public int countKeyChanges(String s) {
int changes = 0;
for (int i = 1; i < s.length(); i++) {
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(i - 1))) {
changes++;
}
}
return changes;
}
}
int countKeyChanges(string s) {
int changes = 0;
for (int i = 1; i < (int)s.size(); i++) {
if (tolower(s[i]) != tolower(s[i - 1])) {
changes++;
}
}
return changes;
}
Explanation
A "key change" happens whenever a character is typed on a different physical key than the one before it. The only twist is that the shift / caps-lock modifier does not count as a key, so 'a' and 'A' are the same key.
The clean way to neutralize case is to compare the lowercased version of each character with the lowercased version of its predecessor. If they differ, a real key change occurred.
We start the loop at index 1 (the first keystroke has nothing before it, so it can never be a change) and keep a running changes counter. For each position i, we compare s[i] with s[i-1] after lowercasing both.
Every time the two differ we add one to changes. When the loop ends, changes holds the total number of times the user switched keys.
Example: s = "aAbBcC". Pairs (a,A) and (b,B) and (c,C) are the same key, but (A,b) and (B,c) are changes, giving a total of 2.