Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- Sherlock and the Valid String
- algospot
- codesignal
- algorithm
- java
- dynamic programming
- 최단 경로 알고리즘
- 명령 프롬프트
- centuryFromYear
- Math.ceil
- Alternating Characters
- 동적 계획법
- 다익스트라
- 문자열
- Making Anagrams
- hacker rank
- ACM-ICPC
- Dynamic Programing
- 01 타일
- Dijkstra
- JUMPGAME
Archives
- Today
- Total
Florescence
Sherlock and the Valid String 본문
Sherlock and the Valid String | HackerRank
Remove some characters from the string such that the new string's characters have the same frequency.
www.hackerrank.com
- 풀이
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the isValid function below.
static String isValid(String str) {
final String YES = "YES";
final String NO = "NO";
char[] ch = str.toCharArray();
Map<String, Integer> map = new HashMap<>();
Map<Integer, Integer> freq = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
map.put(String.valueOf(ch[i]), 0);
}
for (int i = 0; i < str.length(); i++) {
String key = String.valueOf(ch[i]);
int val = map.get(key) + 1;
map.put(key, val);
}
for (String s : map.keySet()) {
int key = map.get(s);
freq.put(key, 0);
}
for (String s : map.keySet()) {
int key = map.get(s);
int val = freq.get(key) + 1;
freq.put(key, val);
}
if (freq.size() == 1)
return YES;
if (freq.size() == 2) {
List<Integer> keySet = new ArrayList<>();
for(int i : freq.keySet()) {
keySet.add(i);
}
int maxKey = Math.max(keySet.get(0), keySet.get(1));
if(Math.abs(keySet.get(0)-keySet.get(1)) == 1 && freq.get(maxKey) == 1) {
return YES;
}
int minKey = Math.min(keySet.get(0), keySet.get(0));
if(minKey == 1 && freq.get(minKey) == 1) {
return YES;
}
}
return NO;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String s = scanner.nextLine();
String result = isValid(s);
bufferedWriter.write(result);
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
- NOTE
- 문자열 저장 후, 빈도 수 저장
- 빈도 수 저장 Map의 크기가 1이면 한 가지 문자만 나온 것이므로 YES
- 빈도 수 저장 Map의 크기가 2이면
- 키 값의 차이가 1이고 키 값 중 큰 값의 value가 1인 경우에만 YES
- 키 값이 1이고, 키가 1인 value 값이 1인 경우에만 YES
- 빈도 수 저장 Map의 크기가 2보다 크면 NO
- String manipulation이라 해서 꼭 배열을 쓸 필요없다 -> 배열로만 생각하다가 시간이 오래 걸림
'Algorithm > Hacker Rank' 카테고리의 다른 글
Making Anagrams (0) | 2020.01.06 |
---|---|
Alternating Characters (0) | 2020.01.06 |