Java/Algorithm

[Java-Algorithm] HackerRank Java - Sherlock and the Valid String 풀이

Jeong Jeon
반응형

1). 문제 : www.hackerrank.com/challenges/sherlock-and-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

2). 풀이 :

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 alternatingCharacters function below.
    static int alternatingCharacters(String s) {
        int cnt = 0;
        
        //A와 B 이어진것 찾아서 지우기
        for(int i=0; i<s.length()-1; i++){
            if(s.substring(i,i+1).equals(s.substring(i+1,i+2))){
                cnt++;
            }
        }
        return cnt;
    }

    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")));

        int q = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int qItr = 0; qItr < q; qItr++) {
            String s = scanner.nextLine();

            int result = alternatingCharacters(s);

            bufferedWriter.write(String.valueOf(result));
            bufferedWriter.newLine();
        }

        bufferedWriter.close();

        scanner.close();
    }
}

반응형