leetcode 204/187/205 Count Primes/Repeated DNA Sequences/Isomorphic Strings

一:leetcode 204 Count Primes

题目:

Description:

Count the number of prime numbers less than a non-negative number, n

分析:此题的算法源码可以参看这里,http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

代码:

class Solution {
public:
    int countPrimes(int n) {     // 求小于一个数n的素数个数 方法思想
        bool *isPrimes = new bool[n];
        memset(isPrimes, 0, sizeof(bool)*(n));
        int ans = 0;
        for(int i = 2; i < n; i++){
            while(i < n && isPrimes[i]) i++;
			if(i >= n) break;
            ans ++;
            for(int j = 2; j <= (n-1)/i; j++)
                isPrimes[j*i] = 1;
        }
        delete []isPrimes;
        return ans;
    }
};

二:leetcode 187  Repeated DNA Sequences

题目:

All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.

Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.

For example,

Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",

Return:
["AAAAACCCCC", "CCCCCAAAAA"].
分析:此题可以看做是判重,可以采用hash_table或者trie树,但是此题对内存要求比较严格,用map<string, int>则会memory limit,此外我这里写的trie树也会memory limit, 

因此使用hashtable的话就必须找到hash函数将string转换为int,一是可以自己编写hash函数或者是用c++11自带的hash<string>。

代码:

一:hashtable

class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
        vector<string> result;
        hash<string> hash_func;            // 将string转换为int的hash函数
        for(int i = 0; i < s.size(); i++){
            string str = s.substr(i, 10);
            if(str.size() < 10)
                break;
           int x = hash_func(str);
			if(hmap.count(x)){
				if(hmap[x] == 1)result.push_back(str);
				hmap[x]++;
			} 
            else hmap.insert(pair<int, int>(x, 1));
        }
        return result;
    }
private:
    unordered_map<int, int> hmap;  // c++的STL中map/set用string会消耗很多memory
};
或者用自己写的hash table:

class Solution {
public:
	int strToInt(const string &str){
		int result = 0;
		for(int i = 0; i < 10; i++){
			switch(str[i])
			{
			case 'A':
				result += 0;
				break;
			case 'C':
				result += 1;
				break;
			case 'G':
				result += 2;
				break;
			case 'T':
				result += 3;
				break;
			}
			result = (result << 2);
		}
		return result;
	}
    vector<string> findRepeatedDnaSequences(string s) {
        vector<string> result;
        hash<string> hash_func;            // 将string转换为int的hash函数
        for(int i = 0; i < s.size(); i++){
            string str = s.substr(i, 10);
            if(str.size() < 10)
                break;
           // int x = hash_func(str);
			int x = strToInt(str);
			if(hmap.count(x)){
				if(hmap[x] == 1)result.push_back(str);
				hmap[x]++;
			} 
            else hmap.insert(pair<int, int>(x, 1));
        }
        return result;
    }
private:
    unordered_map<int, int> hmap;  // c++的STL中map/set用string会消耗很多memory
};

二:trie树的代码——会memory limit

struct TrieNode{
    TrieNode *node[5];
    int count;
    TrieNode():count(1){
        for(int i = 0; i < 5; i++){
            node[i] = NULL;
        }
    }
};


class Solution {
private:
    void destroy(TrieNode *p){
        if(p != NULL){
            for(int i = 0; i < 5; i++)
				destroy(p->node[i]);
            delete p;
        }
    }    
public:
    bool isExist(TrieNode *p, const string &str){
        bool flag = true;
        for(int i = 0; i < str.size(); i++){
            int index = (str[i]-'A') % 5;
            if(p->node[index] == NULL){
                p->node[index] = new TrieNode();
                flag = false;
            }
            p = p->node[index];
        }
        if(flag){
            if(p->count != 1) flag = false;
            p->count ++;
        }
        return flag;
        
    }
    vector<string> findRepeatedDnaSequences(string s) {
        vector<string> result;
        TrieNode *root = new TrieNode();
        for(int i = 0; i < s.size(); i++){
            string str = s.substr(i, 10);
            if(str.size() < 10) break;
            if(isExist(root, str)) result.push_back(str);
        }
        destroy(root);
        return result;
    }
    
};
三:leetcode 205  Isomorphic Strings

题目:

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,
Given "egg""add", return true.

Given "foo""bar", return false.

Given "paper""title", return true.

Note:
You may assume both s and t have the same length.

分析:此时是判断两个字符串是否同构,两边必须都是一一映射,所以我这里采用了两个hash_map

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if(s == t) return true;
        int m = s.size(), n = t.size();
        if(m != n) return false;
        for(int i = 0; i < m; i++){
            if(lmap.count(s[i]) && lmap[s[i]] != t[i]) return false;
            else
               lmap.insert(pair<char, char>(s[i], t[i])); 
               
            if(rmap.count(t[i]) && rmap[t[i]] != s[i]) return false;
            else
               rmap.insert(pair<char, char>(t[i], s[i])); 
        }
        return true;
    }
private:
    unordered_map<char, char> lmap;    // 分别建立了左右两个hash table
    unordered_map<char, char> rmap;
};





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值