LeetCode 刷题【187. 重复的DNA序列】

187. 重复的DNA序列

自己做

解:哈希

java 复制代码
class Solution {
    public List<String> findRepeatedDnaSequences(String s) {
        List<String> res = new ArrayList<>();
        int n = s.length();
        if (n <= 10) {
            return res;
        }

        // 哈希表:key=10长度子串,value=出现次数
        HashMap<String, Integer> countMap = new HashMap<>();

        // 遍历所有10长度子串,统计次数
        for (int i = 0; i <= n - 10; i++) {
            String sub = s.substring(i, i + 10);
            countMap.put(sub, countMap.getOrDefault(sub, 0) + 1);
        }

        // 收集出现次数≥2的子串
        for (String key : countMap.keySet()) {
            if (countMap.get(key) >= 2) {
                res.add(key);
            }
        }

        return res;
    }
}

看题解

java 复制代码
class Solution {
    static final int L = 10;
    Map<Character, Integer> bin = new HashMap<Character, Integer>() {{
        put('A', 0);
        put('C', 1);
        put('G', 2);
        put('T', 3);
    }};

    public List<String> findRepeatedDnaSequences(String s) {
        List<String> ans = new ArrayList<String>();
        int n = s.length();
        if (n <= L) {
            return ans;
        }
        int x = 0;
        for (int i = 0; i < L - 1; ++i) {
            x = (x << 2) | bin.get(s.charAt(i));
        }
        Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();
        for (int i = 0; i <= n - L; ++i) {
            x = ((x << 2) | bin.get(s.charAt(i + L - 1))) & ((1 << (L * 2)) - 1);
            cnt.put(x, cnt.getOrDefault(x, 0) + 1);
            if (cnt.get(x) == 2) {
                ans.add(s.substring(i, i + L));
            }
        }
        return ans;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/repeated-dna-sequences/solutions/1035568/zhong-fu-de-dnaxu-lie-by-leetcode-soluti-z8zn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
2401_841495641 天前
【数据结构】英文单词词频统计与检索系统
数据结构·c++·算法·排序·词频统计·查找·单词检索
独自破碎E1 天前
【迭代+动态规划】把数字翻译成字符串
算法·动态规划
sunfove1 天前
从信息熵到决策边界:决策树算法的第一性原理与深度解析
算法·决策树·机器学习
Niuguangshuo1 天前
CLIP:连接图像与文本的 AI 核心工具
人工智能·神经网络·算法
sali-tec1 天前
C# 基于OpenCv的视觉工作流-章13-边缘提取
人工智能·opencv·算法·计算机视觉
kaikaile19951 天前
基于MATLAB的PSO-ELM(粒子群优化极限学习机)算法实现
深度学习·算法·matlab
YuTaoShao1 天前
【LeetCode 每日一题】1895. 最大的幻方——(解法二)前缀和优化
linux·算法·leetcode
a程序小傲1 天前
中国邮政Java面试被问:边缘计算的数据同步和计算卸载
java·服务器·开发语言·算法·面试·职场和发展·边缘计算
苦藤新鸡1 天前
21.在有序的二位数组中用O(m+n)的算法找target
算法
小尧嵌入式1 天前
【Linux开发二】数字反转|除数累加|差分数组|vector插入和访问|小数四舍五入及向上取整|矩阵逆置|基础文件IO|深入文件IO
linux·服务器·开发语言·c++·线性代数·算法·矩阵