From 1e81ef27100c8fc76bc38ec0135a4b18554398af Mon Sep 17 00:00:00 2001 From: Beim <73528776+162-jld@users.noreply.github.com> Date: Sun, 1 May 2022 11:51:11 +0800 Subject: [PATCH] =?UTF-8?q?Update=200383.=E8=B5=8E=E9=87=91=E4=BF=A1.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0383.赎金信.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 00707347..56dcb8dd 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -110,23 +110,25 @@ Java: ```Java class Solution { public boolean canConstruct(String ransomNote, String magazine) { - //记录杂志字符串出现的次数 - int[] arr = new int[26]; - int temp; - for (int i = 0; i < magazine.length(); i++) { - temp = magazine.charAt(i) - 'a'; - arr[temp]++; + // 定义一个哈希映射数组 + int[] record = new int[26]; + + // 遍历 + for(char c : magazine.toCharArray()){ + record[c - 'a'] += 1; } - for (int i = 0; i < ransomNote.length(); i++) { - temp = ransomNote.charAt(i) - 'a'; - //对于金信中的每一个字符都在数组中查找 - //找到相应位减一,否则找不到返回false - if (arr[temp] > 0) { - arr[temp]--; - } else { + + for(char c : ransomNote.toCharArray()){ + record[c - 'a'] -= 1; + } + + // 如果数组中存在负数,说明ransomNote字符串总存在magazine中没有的字符 + for(int i : record){ + if(i < 0){ return false; } } + return true; } }