Florescence

Sherlock and the Valid String 본문

Algorithm/Hacker Rank

Sherlock and the Valid String

마산와사비 2020. 1. 7. 16:35
 

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
Comments