演算法:雜湊表理論知識

來源:互聯網
上載者:User
一、雜湊表 1.定義

  散列表(Hash table,也叫雜湊表),是根據鍵(Key)而直接存取在記憶體儲存位置的資料結構。也就是說,它通過計算一個關於索引值的函數,將所需查詢的資料對應到表中一個位置來訪問記錄,這加快了尋找速度。這個映射函數稱做散列函數,存放記錄的數組稱做散列表2.基礎概念

1>若關鍵字為k,則其值存放在f(k)的儲存位置上。由此,不需比較便可直接取得所查記錄。稱這個對應關係f散列函數,按這個思想建立的表為散列表

2>對不同的關鍵字可能得到同一散列地址,即k1 != k2,而 f(k1) = f(k2),這種現象稱為衝突(英語:Collision)。具有相同函數值的關鍵字對該散列函數來說稱做同義字

3>若對於關鍵字集合中的任一個關鍵字,經散列函數映象到地址集合中任何一個地址的機率是相等的,則稱此類散列函數為均勻散列函數(Uniform Hash function),這就是使關鍵字經過散列函數得到一個“隨機的地址”,從而減少衝突。 二、演算法使用雜湊 1.題目描述

Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Note:
You may assume the string contains only lowercase alphabets. 2.使用雜湊表思想來解決

Algorithm

To examine if tt is a rearrangement of ss, we can count occurrences of each letter in the two strings and compare them. Since both ss and tt contain only letters from a-za−z, a simple counter table of size 26 is suffice.

Do we need two counter tables for comparison? Actually no, because we could increment the counter for each letter in ss and decrement the counter for each letter in tt, then check if the counter reaches back to zero.

    /**     * 判斷字串s和t是否為迴文構詞法     * @param s     * @param t     * @return     */    public static boolean isAnagram(String s, String t) {        //特殊情況處理        if (s.length() != t.length())            return false;        int[] counter = new int[26];        //通過散列函數f(k) = k - 'a',將字元k 映射到counter數組上        for(int i = 0; i < s.length(); i++){            counter[s.charAt(i) - 'a']++;            counter[t.charAt(i) - 'a']--;        }        for (int count : counter){            if (count != 0)                return false;        }        return true;    } 

額外說明:
這個判斷迴文構詞法演算法中:鍵是字元 k,且字元k 的取值範圍是 [‘a’,’z’],散列函數f(k) = k -‘a’。則f(k)範圍為[0,25];所以可以使用int[] counter = new int[26]; 一個大小為26的數組作為散列表。

擴充:
此處散列方法是直接定址法:取關鍵字或關鍵字的某個線性函數值為散列地址。即 f(k)=a * k + b,其中 a, b均為常數。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.