3019. Number of Changing Keys
Problem
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.
https://leetcode.cn/problems/number-of-changing-keys/
Example 1:
Input:
s = "aAbBcC"
Output:2
Explanation:
Froms[0] = 'a'tos[1] = 'A', there is no change of key as caps lock or shift is not counted.
Froms[1] = 'A'tos[2] = 'b', there is a change of key.
Froms[2] = 'b'tos[3] = 'B', there is no change of key as caps lock or shift is not counted.
Froms[3] = 'B'tos[4] = 'c', there is a change of key.
Froms[4] = 'c'tos[5] = 'C', there is no change of key as caps lock or shift is not counted.
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 <= 100sconsists of only upper case and lower case English letters.
Test Cases
class Solution:
def countKeyChanges(self, s: str) -> int:import pytest
from solution import Solution
@pytest.mark.parametrize('s, expected', [
("aAbBcC", 2),
("AaAaAaaA", 0),
])
@pytest.mark.parametrize('sol', [Solution()])
def test_solution(sol, s, expected):
assert sol.countKeyChanges(s) == expected
Thoughts
直接把 s 转为小写,比较前后两个字符是否相等。
Code
class Solution:
def countKeyChanges(self, s: str) -> int:
s = s.lower()
return sum(s[i] != s[i-1] and 1 or 0 for i in range(1, len(s)))
评论需要 JavaScript。