LeetCode 1897. Redistribute Characters to Make All Strings Equal【字符串/哈希表】简单
发布日期:2021-07-01 03:02:26
浏览次数:2
分类:技术文章
本文共 1435 字,大约阅读时间需要 4 分钟。
You are given an array of strings words
(0-indexed).
In one operation, pick two distinct indices i
and j
, where words[i]
is a non-empty string, and move any character from words[i]
to any position in words[j]
.
Return true
if you can make every string in words
equal using any number of operations, and false
otherwise.
Example 1:
Input: words = ["abc","aabc","bc"]Output: trueExplanation: Move the first 'a' in words[1] to the front of words[2],to make words[1] = "abc" and words[2] = "abc".All the strings are now equal to "abc", so return true.
Example 2:
Input: words = ["ab","a"]Output: falseExplanation: It is impossible to make all the strings equal using the operation.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consists of lowercase English letters.
题意:给你一个字符串数组 words
(下标 从 0 开始 计数)。在一步操作中,需先选出两个 不同 下标 i
和 j
,其中 words[i]
是一个非空字符串,接着将 words[i]
中的 任一 字符移动到 words[j]
中的 任一 位置上。
如果执行任意步操作可以使 words
中的每个字符串都相等,返回 true
;否则,返回 false
。
解法 哈希表
检查每种字符是否可以平均分到所有字符串:
class Solution { public: bool makeEqual(vector& words) { int cnt[26] = { 0}, n = words.size(); for (int i = 0; i < n; ++i) for (int j = 0, m = words[i].size(); j < m; ++j) ++cnt[words[i][j] - 'a']; for (int i = 0; i < 26; ++i) if (cnt[i] % n != 0) return false; return true; }};
运行效率如下:
执行用时:8 ms, 在所有 C++ 提交中击败了99.56% 的用户内存消耗:11.2 MB, 在所有 C++ 提交中击败了89.99% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/117917135 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月19日 12时34分14秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
基于java的ssm框架就业信息管理系统的设计
2019-04-30
Oracle字符串分隔符替换(替换奇数个或偶数个)
2019-04-30
Oracle 利用 UTL_SMTP 包发送邮件
2019-04-30
Oracle的pfile和spfile的一点理解和笔记
2019-04-30
2021-05-18
2019-04-30
基础架构系列篇-NGINX部署VUE
2019-04-30
基础架构系列篇-系统centos7安装kafka
2019-04-30
2021年不可错过的17种JS优化技巧(一)
2019-04-30
在 Vue 中用 Axios 异步请求API
2019-04-30
MySQL进阶查询(SELECT 语句高级用法)
2019-04-30
Mysql 之主从复制
2019-04-30
【NLP学习笔记】中文分词(Word Segmentation,WS)
2019-04-30
对于时间复杂度的通俗理解
2019-04-30
如何输入多组数据并输出每组数据的和?
2019-04-30
行阶梯型矩阵
2019-04-30
JAVA学习笔记6 - 数组
2019-04-30
【学习笔记】Android Activity
2019-04-30
location区段
2019-04-30
linux内存的寻址方式
2019-04-30
how2heap-double free
2019-04-30