• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
THE WAY I AM
博客园    首页    新随笔    联系   管理    订阅  订阅
1002. Find Common Characters查找常用字符

参考:https://leetcode.com/problems/find-common-characters/discuss/247573/C%2B%2B-O(n)-or-O(1)-two-vectors

地址:https://leetcode.com/problems/find-common-characters/

  1. vector初始化:vector<int> a(7,3) // 把a初始化为包含7个值为3的int
  2. char转化为string:string(1,ch)
  3. for (auto s : A)
  4. 使用min
class Solution {
public:
    vector<string> commonChars(vector<string>& A) {
        vector<int> cnt(26, INT_MAX);
        vector<string> res;

        for (auto s : A)
        {
            vector<int> cnt1(26, 0);
            for (auto c : s)
                cnt1[c - 'a'] ++;
            for (auto i = 0; i < 26; ++i)
                cnt[i] = min(cnt[i], cnt1[i]);
        }

        for (auto i = 0; i < 26; ++i)
            for (auto j = 0; j < cnt[i]; ++j)
                res.push_back(string(1, i + 'a'));
        return res;
    }
};

 

posted on 2019-03-11 23:33  549  阅读(143)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3