File tree Expand file tree Collapse file tree 2 files changed +16
-14
lines changed Expand file tree Collapse file tree 2 files changed +16
-14
lines changed Original file line number Diff line number Diff line change 254
254
33 . [ 二叉树:构造一棵搜索树] ( ./problems/0108.将有序数组转换为二叉搜索树.md )
255
255
34 . [ 二叉树:搜索树转成累加树] ( ./problems/0538.把二叉搜索树转换为累加树.md )
256
256
35 . [ 二叉树:总结篇!(需要掌握的二叉树技能都在这里了)] ( ./problems/二叉树总结篇.md )
257
-
257
+
258
258
## 回溯算法
259
259
260
260
题目分类大纲如下:
Original file line number Diff line number Diff line change @@ -114,23 +114,25 @@ Java:
114
114
``` Java
115
115
class Solution {
116
116
public boolean canConstruct (String ransomNote , String magazine ) {
117
- // 记录杂志字符串出现的次数
118
- int [] arr = new int [26 ];
119
- int temp;
120
- for (int i = 0 ; i < magazine. length(); i++ ) {
121
- temp = magazine. charAt(i) - ' a' ;
122
- arr[temp]++ ;
117
+ // 定义一个哈希映射数组
118
+ int [] record = new int [26 ];
119
+
120
+ // 遍历
121
+ for (char c : magazine. toCharArray()){
122
+ record[c - ' a' ] += 1 ;
123
+ }
124
+
125
+ for (char c : ransomNote. toCharArray()){
126
+ record[c - ' a' ] -= 1 ;
123
127
}
124
- for (int i = 0 ; i < ransomNote. length(); i++ ) {
125
- temp = ransomNote. charAt(i) - ' a' ;
126
- // 对于金信中的每一个字符都在数组中查找
127
- // 找到相应位减一,否则找不到返回false
128
- if (arr[temp] > 0 ) {
129
- arr[temp]-- ;
130
- } else {
128
+
129
+ // 如果数组中存在负数,说明ransomNote字符串总存在magazine中没有的字符
130
+ for (int i : record){
131
+ if (i < 0 ){
131
132
return false ;
132
133
}
133
134
}
135
+
134
136
return true ;
135
137
}
136
138
}
You can’t perform that action at this time.
0 commit comments