zoukankan      html  css  js  c++  java
  • LeetCode-187. Repeated DNA Sequences

    这个题是检测子串的重复次数。开始想当然的想到通过s.substring依次取出10个字符串,然后通过equal去比较是否相同。虽然结果可以,但是毫无疑问,时间复杂度O(n2)超时。

    第一层遍历是无法避免的,可以优化的是对字串的对比。类似于字串问题,可以转换为字节操作。因此修改代码如下:

    public class Solution {
        public List<String> findRepeatedDnaSequences(String s) {
            
            List<String> resultlist = new ArrayList<>();   //最终的结果
            int key = 0;
            if (s.length()==0)
            {
                return resultlist;
            }
    
            HashMap<Character,Integer> map = new HashMap<Character, Integer>();    //对四种字母进行编码,可以减少存储空间,同时加快比较速度
            map.put('A',0);
            map.put('C',1);
            map.put('G',2);
            map.put('T',3);
            HashMap<Integer,Integer> result = new HashMap<Integer, Integer>();
    
            for(int i=0;i<s.length();i++)
            {
                key = (key<<2 | map.get(s.charAt(i)) & 0x3) & 0xfffff;  //00.01.10.11可以分别表示四种字符,占2位。每次一个左移2位,通过&0x3可以取出后两位。fffff固定取2*10位
                if(i<9) continue;
                if (result.get(key) == null) {
                    result.put(key, 1);
                } else if (result.get(key) == 1) {
                    resultlist.add(s.substring(i - 9, i + 1));
                    result.put(key, 2);
                }
            }
    
    
            return resultlist;
        }
    }
  • 相关阅读:
    arduino电子艺术PWM直流电机电调实验
    横坐标轴移动位置
    将不才则三军倾
    Source Insight常用快捷键及注释快捷键设置
    dos2unix批量转换的脚本
    win8: ListView
    win8: Asynchronous Programming in JavaScript with “Promises”
    WindJS 中的$await
    iphone:关于沙盒 存储路径
    win8: hello gril
  • 原文地址:https://www.cnblogs.com/ren-jie/p/5267169.html
Copyright © 2011-2022 走看看