判斷“資源字符串”是否可以構成“目標字符串”

題目:Ransom Note

描述:

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true

翻譯:

大概意思就是傳入一個任意字符串和一個其他字符串,判斷第二個字符串可不可以拆分開,構成第一個任意字符串

答案:

第一版答案:(效率低,不滿意,大概思路是統計這兩個字符串中的每個字符的出現次數,並放到兩個不同的Map中存起來,再循環遍歷由任意字符串生成的Map,來看對應的key再第二個Map中是否存在,如果不存在,就肯定不能構成,如果存在,則判斷次數大小,如果第二個map中的次數小,則也不能構成,思路雖然清晰,但是效率比較低。。。貼代碼,稍微有點亂,講道理,應該把其中一段抽成一個公用的方法的)

public boolean canConstruct(String ransomNote, String magazine) {
        int ransomNoteSize = ransomNote.length();
        int magazineSize = magazine.length();
        if (magazineSize < ransomNoteSize)
            return false;
        Map<String, Integer> target = new HashMap<>();
        Map<String, Integer> factory = new HashMap<>();
        for (int i=0; i<magazineSize; i++){
            if (i < ransomNoteSize) {
                char c = ransomNote.charAt(i);
                Integer num = target.get(c + "");
                if (num == null)
                    target.put(ransomNote.charAt(i) + "", 1);
                else
                    target.put(ransomNote.charAt(i) + "", ++num);
            }
            char c = magazine.charAt(i);
            Integer num = factory.get(c + "");
            if (num == null)
                factory.put(magazine.charAt(i) + "", 1);
            else
                factory.put(magazine.charAt(i) + "", ++num);

        }
        Set<String> keys = target.keySet();
        for (String key : keys) {
            if (factory.containsKey(key)){
                Integer val = target.get(key);
                if (val > factory.get(key))
                    return false;
            } else
                return false;
        }
        return true;
    }

第二個方法:由於上面方法確實效率很低,因此上網搜了一下別人的解決辦法,最後寫出瞭如下方法:

public boolean canConstruct(String ransomNote, String magazine) {
        int ransomNoteSize = ransomNote.length();
        int magazineSize = magazine.length();
        if (magazineSize < ransomNoteSize)
            return false;
        int[] target = new int[26];
        char a = 'a';
        for (int i=0; i<magazineSize; i++)
            target[magazine.charAt(i) - a]++;

        for (int i=0; i<ransomNoteSize; i++) {
            if (--target[ransomNote.charAt(i)- a] < 0)
                return false;
        }
        return true;
    }
上面這個方法主要是運用一個26位的數組,每個字母對應一位,和我的第一個方法類似,首先將magazine這個字符串中的每個字符出現的次數統計出來。
再循環遍歷ransomNote這個字符串,遍歷到一個字符串,就將target數組中字符對應的位置的數字減1,再判斷這個位置的字符數量,

如果小於0,則肯定不能構成目標字符串,如果一直大於等於0,則能夠構成目標字符串,最後返回true。

性能差異:第一個方法耗時138ms,第二個方法耗時18ms

發佈了54 篇原創文章 · 獲贊 16 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章