Java/Algorithm

[Java-Algorithm] HackerRank Java - Sherlock and Anagrams 풀이

Jeong Jeon
반응형

1). 문제 : www.hackerrank.com/challenges/sherlock-and-anagrams/

 

Sherlock and Anagrams | HackerRank

Find the number of unordered anagramic pairs of substrings of a string.

www.hackerrank.com

2). 풀이 :

 

Comparator를 알고있는지 모르는지에 대한 문제였던것 같다.

compareTo를 사용했을때 클때, 같을때 작을때 1, 0, -1 을 return하는것만 알고있으면 비교할때 쉬울수있는 문제.

import java.util.*;

class Player {
	String name;
	int score;

	Player(String name, int score) {
		this.name = name;
		this.score = score;
	}
}

class Checker implements Comparator<Player> {
  	// complete this method
	public int compare(Player a, Player b) {
        int result = 0;
        
        if(a.score<b.score){
            result = 1;
        }else if(a.score>b.score){
            result = -1;
        }else{
            return a.name.compareTo(b.name);
        }
        
        return result;
    }
}


public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        Player[] player = new Player[n];
        Checker checker = new Checker();
        
        for(int i = 0; i < n; i++){
            player[i] = new Player(scan.next(), scan.nextInt());
        }
        scan.close();

        Arrays.sort(player, checker);
        for(int i = 0; i < player.length; i++){
            System.out.printf("%s %s\n", player[i].name, player[i].score);
        }
    }
}
반응형