mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Merge pull request #1270 from 162-jld/master
Update 0383.赎金信.md Java解法,代码更简洁
This commit is contained in:
@ -254,7 +254,7 @@
|
||||
33. [二叉树:构造一棵搜索树](./problems/0108.将有序数组转换为二叉搜索树.md)
|
||||
34. [二叉树:搜索树转成累加树](./problems/0538.把二叉搜索树转换为累加树.md)
|
||||
35. [二叉树:总结篇!(需要掌握的二叉树技能都在这里了)](./problems/二叉树总结篇.md)
|
||||
|
||||
|
||||
## 回溯算法
|
||||
|
||||
题目分类大纲如下:
|
||||
|
@ -114,23 +114,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;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user