[LeetCode] Number of Changing Keys

3019. Number of Changing Keys

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int countKeyChanges(string s) {
int res = 0;
for(int i = 0; i < s.length() - 1; i++) {
char a = s[i], b = s[i+1];
if(isupper(a)) a = tolower(a);
if(isupper(b)) b = ::tolower(b);
if(a != b) res += 1;
}
return res;
}
};


Author: Song Hayoung
Link: https://songhayoung.github.io/2024/01/28/PS/LeetCode/number-of-changing-keys/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.