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.
Input: s ="aAbBcC"Output: 2Explanation:
From s[0]='a' to s[1]='A', there is no change of key as caps lock or shift is not counted.From s[1]='A' to s[2]='b', there is a change of key.From s[2]='b' to s[3]='B', there is no change of key as caps lock or shift is not counted.From s[3]='B' to s[4]='c', there is a change of key.From s[4]='c' to s[5]='C', there is no change of key as caps lock or shift is not counted.
Input: s ="AaAaAaaA"Output: 0Explanation: There is no change of key since only the letters 'a' and 'A' are pressed which does not require change of key.
#include<string>usingnamespace std;
classSolution {
public:int countChangingKeys(string s) {
int cnt =0;
for (int i =1; i < s.size(); ++i)
if (tolower(s[i]) != tolower(s[i-1])) ++cnt;
return cnt;
}
};
1
2
3
4
5
6
7
8
9
10
import"strings"funccountChangingKeys(sstring) int {
cnt:=0fori:=1; i < len(s); i++ {
ifstrings.ToLower(string(s[i])) !=strings.ToLower(string(s[i-1])) {
cnt++ }
}
returncnt}
1
2
3
4
5
6
7
8
classSolution {
publicintcountChangingKeys(String s) {
int cnt = 0;
for (int i = 1; i < s.length(); ++i)
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(i-1))) cnt++;
return cnt;
}
}
1
2
3
4
5
6
7
8
classSolution {
funcountChangingKeys(s: String): Int {
var cnt = 0for (i in1 until s.length)
if (s[i].lowercaseChar() != s[i-1].lowercaseChar()) cnt++return cnt
}
}
1
2
3
classSolution:
defcountChangingKeys(self, s: str) -> int:
return sum(s[i].lower() != s[i-1].lower() for i in range(1, len(s)))
1
2
3
4
5
6
7
8
9
10
impl Solution {
pubfncount_changing_keys(s: String) -> i32 {
let bytes = s.as_bytes();
letmut cnt =0;
for i in1..bytes.len() {
if bytes[i].to_ascii_lowercase() != bytes[i-1].to_ascii_lowercase() { cnt +=1; }
}
cnt
}
}
1
2
3
4
5
6
functioncountChangingKeys(s: string):number {
letcnt=0;
for (leti=1; i<s.length; ++i)
if (s[i].toLowerCase() !==s[i-1].toLowerCase()) cnt++;
returncnt;
}