leetcode-哈希表與字符串

LeetCode-哈希表和字符串

哈希表

hash table, 也叫散列表,把關鍵值key映射爲數組下標進行訪問,映射函數叫做哈希/散列函數,數組叫做哈希/散列表。

// hash table
// record times of char in string

#include <iostream>
#include <string>
int main()
{
	std::string str = "abcdefaaaxxy";
	int charMap[128] = {};
	
	for (int i = 0, nLen = str.length(); i < nLen; ++i)
	{
		++charMap[str[i]];
	}
	for (int i = 0; i < 128; ++i)
	{
		if (charMap[i])
		{
			printf("[%d(%c)]: %d times\n", i, i, charMap[i]);
		}
	}
	return 0;
}

哈希表排序

使用數組下標對正整數排序。哈希表長度需要超過最大待排序數字。

時間複雜度O(表長+n)

#include <iostream>
int main()
{
	int aRand[10] = {999, 1, 333, 7, 20, 9, 1, 3, 7, 7};
	int hashMap[1000] = {};
	
	for (int i = 0; i < 10; ++i)
	{
		++hashMap[aRand[i]];
	}
	for (int i = 0; i < 1000; ++i)
	{
		for (int j = 0; j < hashMap[i]; ++j)
		{
			// 有幾個就打印幾個
			printf("%d\n", i);
		}
	}
	return 0;
}

問題

  1. 遇到負數或很大的數?遇到字符串?其它無法直接映射的類型,如浮點數,數組,類?

答:轉換爲整數再對數組長度取餘。

  1. 如何解決衝突?

答:衝突本質是數組不夠長,可以將哈希表定義爲鏈表數組,頭插法添加元素。


#include <iostream>

struct ListNode {
	int val;
	ListNode* next;
	ListNode(int x) : val(x), next(NULL){}
};

int hash(int key, int nTableLen)
{
	return key % nTableLen;
}
bool insert(ListNode *hashTable[], int nTableLen, ListNode *pNode)
{
	if (!hashTable || !pNode) return false;
	
	int key = hash(pNode->val, nTableLen);
	pNode->next = hashTable[key];
	hashTable[key] = pNode;

	return true;
}
bool search(ListNode* hashTable[], int nTableLen, int val)
{
	if (!hashTable) return false;
	
	int key = hash(val, nTableLen);
	ListNode* pNode = hashTable[key];
	while (pNode)
	{
		if (pNode->val == val) return true;
		pNode = pNode->next;
	}
	return false;
}
int main()
{
	const int nTableLen = 11;
	int aNodes[8] = { 1, 1, 4, 9, 20, 30, 150, 500 };
	ListNode* hashTable[nTableLen] = {};
	for (int i = 0; i < 11; ++i)
	{
		insert(hashTable, nTableLen, new ListNode(aNodes[i]));
	}
	for (int i = 0; i < 11; ++i)
	{
		printf("[%d]: ", i);
		ListNode* pNode = hashTable[i];
		while (pNode)
		{
			printf("->%d", pNode->val);
			pNode = pNode->next;
		}
		printf("\n");
	}
	for (int i = 0; i < 10; ++i)
	{
		if (search(hashTable, nTableLen, i))
		{
			printf("%d in hashTable\n", i);
		}
		else
		{
			printf("%d not in hashTable\n", i);
		}
	}
	return 0;
}
/*
[0]: ->11
[1]: ->1->1
[2]:
[3]:
[4]: ->4
[5]: ->500
[6]:
[7]: ->150
[8]: ->30
[9]: ->20->9
[10]:
0 not in hashTable
1 in hashTable
2 not in hashTable
3 not in hashTable
4 in hashTable
5 not in hashTable
6 not in hashTable
7 not in hashTable
8 not in hashTable
9 in hashTable
*/

LeetCode 409 - Longest Palindrome - 最長迴文串 - easy

給定一個包含大寫字母和小寫字母的字符串,找到通過這些字母構造成的最長的迴文串。

在構造過程中,請注意區分大小寫。比如 “Aa” 不能當做一個迴文字符串。

注意:
假設字符串的長度不會超過 1010。

示例 1:

輸入:
"abccccdd"

輸出:
7

解釋:我們可以構造的最長的迴文串是"dccaccd", 它的長度是 7。

思路:

  1. 數量爲偶數的字符,全部使用,頭尾各放置一半;
  2. 數量爲奇數的字符,丟掉一個按偶數處理;
  3. 剩餘字符,選一個放在中間。
class Solution {
public:
    int longestPalindrome(string s) {
        const int nTableLen = 128;
        int hashMap[nTableLen] = {};
        int nLen = s.length();
        int nMid = 0;
        int nRes = 0;
        for(int i = 0; i < nLen; ++i)
        {
            ++hashMap[s[i]];
        }
        for(int i = 0; i < nTableLen; ++i)
        {
            if(hashMap[i] % 2)
            {
                // odd
                nRes += hashMap[i] - 1;
                nMid = 1;
            }
            else
            {
                nRes += hashMap[i];
            }
        }
        return nRes + nMid;
    }
};

LeetCode 290 - Word Pattern - 單詞規律 - easy

給定一種規律 pattern 和一個字符串 str ,判斷 str 是否遵循相同的規律。

這裏的 遵循 指完全匹配,例如, pattern 裏的每個字母和字符串 str 中的每個非空單詞之間存在着雙向連接的對應規律。

示例1:

輸入: pattern = "abba", str = "dog cat cat dog"
輸出: true

示例 2:

輸入:pattern = "abba", str = "dog cat cat fish"
輸出: false

示例 3:

輸入: pattern = "aaaa", str = "dog cat cat dog"
輸出: false

示例 4:

輸入: pattern = "abba", str = "dog dog dog dog"
輸出: false

說明:你可以假設 pattern 只包含小寫字母, str 包含了由單個空格分隔的小寫字母。


思路,解析出新的單詞,若已出現,則對應一個字符,否則映射爲新的字符。最終字符數和單詞數還要相等。

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        std::map<string, char> mapWord;
        std::string word;
        bool bUsed[128] = {};
        int nLenStr = str.length();
        int nLenPat = pattern.length();
        int nPosPat = 0;

        for(int i = 0; i <= nLenStr; ++i)
        {
            // new word
            if ( str[i] == ' ' || str[i] == '\0')
            {
                // pattern end?
                if ( nPosPat == nLenPat ) return false;
                // word not mapped
                if ( mapWord.find(word) == mapWord.end())
                {
                    if ( bUsed[pattern[nPosPat]])
                    {
                        return false;
                    }
                    mapWord[word] = pattern[nPosPat];
                    bUsed[pattern[nPosPat]] = true;
                     
                }
                // word mapped
                else if(mapWord[word] != pattern[nPosPat])
                {
                    return false;
                }
                word = "";
                ++nPosPat;
            }
            else
            {
                word += str[i];
            }
        }

        if ( nLenPat != nPosPat)
            // 有多餘pattern 
            return false;
        else 
            return true;
    }
};

LeetCode 49 - Group Anagrams - 字母異位詞分組 - medium

給定一個字符串數組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。

示例:

輸入: ["eat", "tea", "tan", "ate", "nat", "bat"]
輸出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

說明:所有輸入均爲小寫字母。不考慮答案輸出的順序。


關鍵是如何把anagram(異位詞)映射到一起。

方法1

可以把排好序的單詞作爲key。

using namespace std;
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        map<string, vector<string>> mapAnagrams;
        vector<vector<string>> vecRes;
        int nSize = strs.size();
        for(int i = 0 ; i < nSize; ++i)
        {
            // strs is a reference
            // so use a tmp var
            string strKey = strs[i];
            sort(strKey.begin(), strKey.end());
            
            // strTmp is a new key
            if(mapAnagrams.find(strKey) == mapAnagrams.end())
            {
                // needn't to alloc
                vector<string> vecItem;
                mapAnagrams[strKey] = vecItem;
            }
            mapAnagrams[strKey].push_back(strs[i]);
        }

        for(map<string, vector<string>>::iterator it = mapAnagrams.begin();
            it != mapAnagrams.end();
            ++it)
        {
            vecRes.push_back((*it).second);
        }
        return vecRes;
    }
};

方法2

用vector存儲各個字母出現次數,作爲key。也就是用另一個哈希表作爲key。標準的用空間換時間。

class Solution {
public:
    void generateVector(string &str, vector<int> &vec)
    {
        int nLen = str.length();
        for(int i = 0; i < nLen; ++i)
        {
            ++vec[str[i] - 'a'];
        }
    }
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        map<vector<int>, vector<string>> mapAnagrams;
        vector<vector<string>> vecRes;
        int nSize = strs.size();
        for(int i = 0 ; i < nSize; ++i)
        {
            vector<int> vecKey(26, 0);
            generateVector(strs[i], vecKey);
            if(mapAnagrams.find(vecKey) == mapAnagrams.end())
            {
                vector<string> vecItem;
                mapAnagrams[vecKey] = vecItem;
            }
            mapAnagrams[vecKey].push_back(strs[i]);
        }
        for(map<vector<int>, vector<string>>::iterator it = mapAnagrams.begin();
            it != mapAnagrams.end();
            ++it)
        {
            vecRes.push_back((*it).second);
        }
        return vecRes;
    }
};

LeetCode 3 - Longest Substring Without Repeating Characters - 無重複字符的最長子串 - medium

給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。

枚舉法複雜度是n方,現在思考O(n)的方法,也就是掃描一遍。

枚舉法的缺陷,一個是會重複掃描已重複的字符,再一個是會枚舉長度短於已知解的子串。

思路:

  1. 定義字符數量哈希表、最長子串string及其長度;
  2. 雙指針,begin指向字符串開頭,p向後掃描,並更新哈希表;
  3. 若掃描到出現過的字符,則前移begin到重複字符後面,並更新哈希表。

這個過程,雙指針維護了一個窗口,併線性滑動(看着有點熟~)。

雙指針常常用來維護一個需要滿足一定條件的窗口。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int mapChar[128] = {};
        int begin = 0;
        int nRes = 0;
        string str;
        
        for(int i = 0, nLen = s.length(); i < nLen; ++i)
        {
            ++mapChar[s[i]];

            // char not in str
            if(mapChar[s[i]] == 1)
            {
                str += s[i];
                if(nRes < str.length())
                {
                    nRes = str.length();
                }
            }
            // char in str
            else
            {
                // 設重複字符第一次出現在索引x處
                // 則要更新begin-x區間的map值
                while( begin < i && mapChar[s[i]] > 1)
                {
                    --mapChar[s[begin]];
                    ++begin;
                }
                str.assign(s, begin, i - begin + 1);
            }
        }
        return nRes;
    }
};

雙指針

參考labuladong大神的框架:

int left = 0, right = 0;

while (right < s.size()) {`
    // 增大窗口
    window.add(s[right]);
    right++;
    
    while (window needs shrink) {
        // 縮小窗口
        window.remove(s[left]);
        left++;
    }
}

LeetCode 187 - Repeated DNA Sequences - 重複的DNA序列 - medium

所有 DNA 都由一系列縮寫爲 A,C,G 和 T 的核苷酸組成,例如:“ACGAATTCCG”。在研究 DNA 時,識別 DNA 中的重複序列有時會對研究非常有幫助。

編寫一個函數來查找目標子串,目標子串的長度爲 10,且在 DNA 字符串 s 中出現次數超過一次。

示例:

輸入:s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
輸出:["AAAAACCCCC", "CCCCCAAAAA"]

枚舉法

class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
        map<string, int> hashMap;
        vector<string> vecRes;
        int nSize = s.length();
        
        for ( int i = 0 ; i < nSize; ++i)
        {
            string str = s.substr(i, 10);
            if(hashMap.find(str) != hashMap.end())
            {
                ++hashMap[str];
            }
            else
            {
                hashMap[str] = 1;
            }
        }
        
        for(map<string, int>::iterator it = hashMap.begin();
            it != hashMap.end();
            ++it)
        {
            if(it->second > 1)
            {
                vecRes.push_back(it->first);
            }
        }
        return vecRes;
    }
};

位運算解法

每個字符AGCT四種情況,2 bit表示,10個字符則是20bit,可作爲key值作爲數組下標。

// too large, so define global var.
int g_hashMap[1048576] = {0};

class Solution {
public:
    Solution()
    {
        
    }
    string key2DNA(int key)
    {
        static char acDNA[4] = {'A', 'C', 'G', 'T'};
        string strRes;
        for(int i = 0; i < 10; ++i)
        {
            strRes += acDNA[key & 3];
            key  = key >> 2;
        }
        return strRes;
    }
    vector<string> findRepeatedDnaSequences(string s) {
        vector<string> vecRes;
        int nLen = s.length();
        if (nLen < 10) return vecRes;
        map<char, int> mapChar;
        mapChar['A'] = 0;
        mapChar['C'] = 1;
        mapChar['G'] = 2;
        mapChar['T'] = 3;
        
        // reset per call
        memset(g_hashMap, 0, sizeof(int) * 1048576);
        
        int key = 0;
        // 先處理前10個字符
        for(int i = 9 ; i >= 0; --i)
        {
            key = (key << 2) + mapChar[s[i]];
        }
        g_hashMap[key] = 1;

        for(int i = 10 ; i < nLen; ++i)
        {
            // 前9個字符
            key = key >> 2;
            // s[i]放在高位
            key = key | mapChar[s[i]] << 18;
            ++g_hashMap[key];
        }
        for(int i = 0; i < 1048576; ++i)
        {
            if(g_hashMap[i] > 1)
                vecRes.push_back(key2DNA(i));
        }
        return vecRes;
    }

};

LeetCode 76 - Minimum Window Substring - hard

給你一個字符串 S、一個字符串 T,請在字符串 S 裏面找出:包含 T 所有字符的最小子串。

示例:

輸入: S = "ADOBECODEBANC", T = "ABC"
輸出: "BANC"

說明:

  • 如果 S 中不存這樣的子串,則返回空字符串 “”。
  • 如果 S 中存在這樣的子串,我們保證它是唯一的答案。

本題雙指針掃描過程:

  • 若begin字符沒有在T中出現,則begin前移;
  • 若begin字符在T中出現,但窗口中存在大於1個該字符,begin也前移,並更新map_s
  • 每移動一次i,檢查是否更新結果子串。
class Solution {
public:
    bool checkWindow(int mapS[], int mapT[], vector<char> setCharInT)
    {
        vector<char>::iterator it;
        for(it = setCharInT.begin(); it != setCharInT.end(); ++it)
        {
            if(mapS[*it] < mapT[*it])
            {
                return false;
            }
        }
        return true;
    }
    string minWindow(string s, string t) {
        const int MAP_SIZE = 128;
        int mapS[MAP_SIZE] = {};
        int mapT[MAP_SIZE] = {};
        vector<char> setCharInT;

        // 先處理T
        int nLenT = t.length();
        for(int i = 0; i < nLenT; ++i)
        {
            ++mapT[t[i]];
        }
        for(int i = 0 ; i < MAP_SIZE; ++i)
        {
            if(mapT[i] > 0)
            {
                setCharInT.push_back(i);
            }
        }


        // scan s
        int begin = 0;
        int nLenS = s.length();
        string strRes;
        for(int i = 0 ; i < nLenS; ++i)
        {
            ++mapS[s[i]];

            // scan window
            while(begin < i)
            {
                char cBegin = s[begin];
                // if s[begin] not in t
                if(mapT[cBegin] == 0)
                {
                    ++begin;
                }
                // if s[begin] in t
                else if (mapS[cBegin] > mapT[cBegin])
                {
                    --mapS[cBegin];
                    ++begin;
                }
                else
                {
                    break;
                }
            }

            // check current result
            if(checkWindow(mapS, mapT, setCharInT))
            {
                int nNewLen = i - begin + 1;
                if (strRes == "" || strRes.length() > nNewLen)
                {
                    strRes = s.substr(begin, nNewLen);
                }
            }
        }

        return strRes;
    }
};

需要用mapS、mapT記錄字符數量。本來是想用set,但超時了。

來自labuladong大神的解法。

unordered_map經常用來代替map,幾種鍵值對容器抽空還得整理對比下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章