383. 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

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

以为要查找note的起点、终点:没必要,太麻烦,不如遍历,表示每个字母都给查

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

不如遍历,表示每个字母都给查

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

int[26]虽然是数字的数组,但是可以统计字母出现的次数,字符串题常用

[关键模板化代码]:

把字符暂存在数字数组里

int[] chars = new int[26];
        //store
        for (char c : magazine.toCharArray()) {
            chars[c - 'a']++;
        }

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        //cc
        //ini
        int[] chars = new int[26];
        //store
        for (char c : magazine.toCharArray()) {
            chars[c - 'a']++;
        }
        //judge
        for (char c : ransomNote.toCharArray()) {
            if (--chars[c - 'a'] < 0) {
                return false;
            }
        }
        //return
        return true;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8601093.html