一道迅雷面試題:求出一個字串中每個字母出現的次數,試題字串

來源:互聯網
上載者:User

一道迅雷面試題:求出一個字串中每個字母出現的次數,試題字串
By Long Luo

個人部落格地址

上次在迅雷面試的時候,遇到了一個演算法題,題目是:

有一個很長很長的字串,全部都是由大寫字母組成,要求求出其中每個字母在這個字串中出現的次數。不允許使用STL中的方法。

當時拿到這個題目,我首先想到了以下幾個方法:

其實這個題目,事後回顧起來,是比較簡單的,但遺憾的是,當時未能在規定時間內解答出來,導致未能通過面試,拿到Offer,在此將這個題目記錄下來。

重新認真解答這個題目。

How?

其實這個題目有一個很簡單的解決防範,建立一個數組,大小為26,將字串中每個字元都與'A'相減,得到的就是每個字母在數組中的元素下標值,我們最後得到的這個數組就是每個字母在這個字串中出現的次數。

根據以上分析,可以寫出如下代碼:

package com.algorithm.alphabetSort;/** * 有一個很長的字串,其中都是一些字母,求其中每個字母出現的次數(大小寫區分)。 *  * @author luolong * @date: 2015-04-12 00:54:17 *  */public class AlphabetSort {    private static String str = "AWQEYIOAHDHDKKLDLAHFHJALAFHANNAFGJCXCKBZCQIEOPADHAZBZVCFGCSHDJCKCLDMDHFAKAIIAYQO";    private static int[] outArray = new int[26];    public static void main(String[] args) {        AlphabetSortString(str);        printSortArray(outArray);    }    public static void AlphabetSortString(String str) {        char cTemp;        for (int i = 0; i < str.length(); i++) {            cTemp = str.charAt(i);            outArray[cTemp - 'A']++;        }    }    private static void printSortArray(int[] arr) {        for (int i = 0; i < arr.length; i++) {            char c = (char) ('A' + i);            System.out.print("" + c + "=" + arr[i] + " ");        }    }}
引申與擴充一

如果字串不僅僅是大寫字母,而是大小寫字母都存在的情況下,那應該如何寫呢?

其實也很簡單,如下所示:

if (cTemp >= 'A' && cTemp <= 'Z') {    /**    * 大寫字母    */    outArray[cTemp - 'A']++;} else if (cTemp >= 'a' && cTemp <= 'z') {    /**    * 小寫字母    */    outArray[cTemp - 'a' + 26]++;} else {}
引申與擴充二

如果字串,假如所有字元都需要統計呢?

那又應該如何做呢?

後來我發現了用HashMap來儲存也是可以的,也可以完美解決這個問題,代碼如下所示:

package com.algorithm.alphabetSort;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;/** * 有一個很長的字串,其中都是一些字母,求其中每個字母出現的次數(大小寫區分)。 *  * @author luolong * @date: 2015-04-12 01:03:38 *  */public class CharSort {    private static String str = "AWQEYIOAHDHDKKLDLAHFHJALAFHANNAFGJCXCKBZCQIEOPADHAZBZVCFGCSHDJCKCLDMDHFAKAIIAYQO";    public static void main(String args[]) {        Map<Character, KeyValue> map = new HashMap<Character, KeyValue>();        char c;        KeyValue kv = null;        for (int i = 0; i < str.length(); i++) {            c = str.charAt(i);            kv = map.get(c);            if (kv == null) {                kv = new KeyValue();                kv.ch = c;                kv.count = 1;                map.put(c, kv);            } else {                kv.count++;            }        }        List<KeyValue> list = new ArrayList<KeyValue>(map.values());        Collections.sort(list);        for (KeyValue o : list) {            System.out.print(o.ch + "=" + o.count + "  ");        }    }}class KeyValue implements Comparable {    public int compareTo(Object obj) {        if (obj instanceof KeyValue) {            KeyValue kv = (KeyValue) obj;            return kv.count - this.count;        }        return -1;    }    char ch;    int count;}

以上。

如果大家還有其他更好的方法,歡迎一起討論:-)

Created by Long Luo at 2015-04-12 01:08:20 @Shenzhen, China.Completed By Long Luo at 2015-04-12 01:28:39 @Shenzhen, China.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.