Leetcode3014. 输入单词需要的最少按键次数 I

Every day a Leetcode

题目来源:3014. 输入单词需要的最少按键次数 I

解法1:统计

统计字符串 word 的小写字母个数和 1、#、*、0 的个数。

将小写字母均匀地分配到 8 个按键上,模拟即可。

代码:

/*
 * @lc app=leetcode.cn id=3014 lang=cpp
 *
 * [3014] 输入单词需要的最少按键次数 I
 */

// @lc code=start
class Solution
{
   
public:
    int minimumPushes(string word)
    {
   
        // 特判
        if (word.empty())
            return 0;

        const string special = "1*#0";
        int count_sp = 0, count_alpha = 0;
        for (char &c : word)
        {
   
            if (special.find(c) != string::npos)
                count_sp++;
            else
                count_alpha++;
        }
        int ans = 0, x = 1;
        while (count_alpha >= 8)
        {
   

            ans += 8 * x;
            x++;
            count_alpha -= 8;
        }
        ans += count_alpha * x + count_sp;
        return ans;
    }
};
// @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(n),其中 n 是字符串 s 的长度。

空间复杂度:O(1)。

解法2:数学

题目里说了字符串 s 中只要小写字母,所以不用统计 1、#、*、0 这 4 个特殊字符的出现次数。

在这里插入图片描述

代码:

// 数学

class Solution
{
   
public:
    int minimumPushes(string word)
    {
   
        // 特判
        if (word.empty())
            return 0;

        int n = word.length();
        int k = n / 8;
        return (k * 4 + n % 8) * (k + 1);
    }
};

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(1)。

空间复杂度:O(1)。

相关推荐

  1. leetCode58. 最后一个单词长度

    2024-01-29 09:50:01       11 阅读
  2. leetcode58 最后一个单词长度

    2024-01-29 09:50:01       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-29 09:50:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-29 09:50:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-29 09:50:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-29 09:50:01       18 阅读

热门阅读

  1. 1.4编程基础之逻辑表达式与条件分支

    2024-01-29 09:50:01       25 阅读
  2. MySQL中四种索引类型

    2024-01-29 09:50:01       29 阅读
  3. 从微服务到云原生

    2024-01-29 09:50:01       34 阅读
  4. 无穷大与无穷小【高数笔记】

    2024-01-29 09:50:01       35 阅读
  5. DAY_10(区间dp)

    2024-01-29 09:50:01       32 阅读
  6. 上线服务器流程用法及说明

    2024-01-29 09:50:01       36 阅读