Skip to content

Commit 657aedb

Browse files
committed
383. Ransom Note
1 parent 02728d5 commit 657aedb

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

383/step1.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
4:25
3+
Space O: O(N)
4+
Time O: O(N)
5+
6+
ransomに使用する文字が十分存在するかどうかをカウントすればよいと考える。
7+
magazineにある文字を高速にチェックできないといけないので、ハッシュ(map)にして高速化を考える。
8+
magazineに存在しない文字や、消費し尽くした文字を指定されたらransomは成立しなくなるのでその時点でfalseを返せる。
9+
falseを返さずに最後までチェックし終えたら
10+
*/
11+
class Solution {
12+
public:
13+
bool canConstruct(string ransomNote, string magazine) {
14+
map<char, int> character_count;
15+
for (char c: magazine) {
16+
if (!character_count[c]) {
17+
character_count[c] = 0;
18+
}
19+
character_count[c]++;
20+
}
21+
22+
for (char c: ransomNote) {
23+
if (!character_count[c] || character_count[c] <= 0) {
24+
return false;
25+
}
26+
character_count[c]--;
27+
}
28+
29+
return true;
30+
}
31+
};

383/step2.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/*
2+
解説や他の人のコードを読んで改良。
3+
おおまかな方針は変えていないが、mapをintの配列にして、charをintとして扱う手法で高速化
4+
*/
5+
class Solution {
6+
public:
7+
bool canConstruct(string ransomNote, string magazine) {
8+
int char_count[26];
9+
for (char c: magazine) {
10+
char_count[c - 97]++;
11+
}
12+
13+
for (char c: ransomNote) {
14+
if (char_count[c - 97] == 0) {
15+
return false;
16+
}
17+
char_count[c - 97]--;
18+
}
19+
20+
return true;
21+
}
22+
};

383/step3.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
97という定数が気持ち悪かったので、'a'に変更、それ以外はstep2と変わらず。
3+
*/
4+
class Solution {
5+
public:
6+
bool canConstruct(string ransomNote, string magazine) {
7+
int char_count[26];
8+
9+
for (char c: magazine) {
10+
char_count[c - 'a']++;
11+
}
12+
13+
for(char c: ransomNote) {
14+
if (char_count[c - 'a'] == 0) {
15+
return false;
16+
}
17+
18+
char_count[c - 'a']--;
19+
}
20+
21+
return true;
22+
}
23+
};

0 commit comments

Comments
 (0)