首页 > 学院 > 开发设计 > 正文

【Leetcode】383. Ransom Note

2019-11-06 08:30:36
字体:
来源:转载
供稿:网友

方法一:

思路:

(1)使用HashMap,将magazine读取入HashMap,key是字符,value是对应该字符的个数。

(2)遍历ransomNote,对HashMap进行操作,若HashMap中不含有该字符,或当前含有的字符个数个数=0,则说明ransomNote中含有的字符,在magazine中没有覆盖到。

public class Solution {    public boolean canConstruct(String ransomNote, String magazine) {        Map<Character, Integer> map = new HashMap<Character, Integer>();        int rLen = ransomNote.length();        int mLen = magazine.length();        if (rLen > mLen)            return false;        for (int i = 0; i < mLen; i++) {            char ch = magazine.charAt(i);            if (map.containsKey(ch))                map.put(ch, map.get(ch) + 1);            else                map.put(ch, 1);        }        for (int i = 0; i < rLen; i++) {            char ch = ransomNote.charAt(i);            if (!map.containsKey(ch) || map.get(ch) == 0)                return false;            map.put(ch, map.get(ch) - 1);        }	   	return true;    }}

Runtime:71ms

方法二:

思路:

建立2个哈希表r、m,分别统计每个字符出现的次数,最后比较r、m的相应字符出现的次数,若r的大,则返回false。

public class Solution {    public boolean canConstruct(String ransomNote, String magazine) {        int rLen = ransomNote.length();        int mLen = magazine.length();        int[] r = new int[26];        int[] m = new int[26];        if (rLen > mLen)            return false;        for (int i = 0; i < rLen; i++)            r[ransomNote.charAt(i) - 'a']++;        for (int i = 0; i < mLen; i++)            m[magazine.charAt(i) - 'a']++;        for (int i = 0; i < 26; i++) {            if (r[i] > m[i])                return false;        }	   	return true;    }}

Runtime:16ms


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表