返回介绍

solution / 3000-3099 / 3019.Number of Changing Keys / README_EN

发布于 2024-06-17 01:02:57 字数 3930 浏览 0 评论 0 收藏 0

3019. Number of Changing Keys

中文文档

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' 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.

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.

Solutions

Solution 1: Single Pass

We can traverse the string, each time checking whether the lowercase form of the current character is the same as the lowercase form of the previous character. If they are different, it means that the key has been changed, and we can increment the answer accordingly.

The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.

class Solution:
  def countKeyChanges(self, s: str) -> int:
    return sum(a.lower() != b.lower() for a, b in pairwise(s))
class Solution {
  public int countKeyChanges(String s) {
    int ans = 0;
    for (int i = 1; i < s.length(); ++i) {
      if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(i - 1))) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int countKeyChanges(string s) {
    transform(s.begin(), s.end(), s.begin(), ::tolower);
    int ans = 0;
    for (int i = 1; i < s.size(); ++i) {
      ans += s[i] != s[i - 1];
    }
    return ans;
  }
};
func countKeyChanges(s string) (ans int) {
  s = strings.ToLower(s)
  for i, c := range s[1:] {
    if byte(c) != s[i] {
      ans++
    }
  }
  return
}
function countKeyChanges(s: string): number {
  s = s.toLowerCase();
  let ans = 0;
  for (let i = 1; i < s.length; ++i) {
    if (s[i] !== s[i - 1]) {
      ++ans;
    }
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文