Hash
HashMap(Key, Value)
Task
์ ํ๋ฒํธ ๋ชฉ๋ก in Programmers (Level 2)
๐ Problem
https://programmers.co.kr/learn/courses/30/lessons/42577
๐ Answer
1. Use HashMap
The point
- HashMap.containsKey(String)
- String.substring(start, end);
- Check the splited number is in map
- HashMap is super quick lol so, if hashmap, multi for loop was also okayโฆ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.HashMap;
class Solution {
public boolean solution(String[] phone_book) {
// put datas of phone_book to HashMap
// Q : why number is key?
// A : because we're gonna use 'HashMap.containsKey(String)''
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < phone_book.length; i++)
map.put(phone_book[i], i);
// check there are num in the map
for (String num : phone_book) {
for (int i = 1; i < num.length(); i++) {
if (map.containsKey(num.substring(0, i)))
return false;
}
}
return true;
}
}
The source : https://coding-grandpa.tistory.com/entry/ํ๋ก๊ทธ๋๋จธ์ค-์ ํ๋ฒํธ-๋ชฉ๋ก-ํด์-Lv-2-์๋ฐ-Java
2. Use Arrays.sort()
The point
- Arrays.sort(String[])
1 2 3 4
ex. before sorting { "99", "7894", "123", "123456", "789" } after sorting { "123", "123456", "789", "7894", "99"}
- String.startsWith(String)
- But it was slower than HashMap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.Arrays;
class Solution {
public boolean solution(String[] phone_book) {
Arrays.sort(phone_book);
// you only need to compare the current number and the next number
// because Arrays.sort();
for (int i = 0; i < phone_book.length - 1; i++)
if (phone_book[i + 1].startsWith(phone_book[i])) return false;
return true;
}
}
The source : https://sso-feeling.tistory.com/318?category=922139
๐ Words
- 2 or more, more than 2: ไปฅไธ
- 2 or less : ไปฅไธ
- over 2, above 2, grater than 2 : ่ถ ้๏ผใกใใใ๏ผ
- under 2, below 2, less than 2 : ๆชๆบ๏ผใฟใพใ๏ผ
Comments powered by Disqus.