algorithm/java

hackerrank/warm up/Repeated String

아르르르를를르 2021. 6. 20. 14:09

https://www.hackerrank.com/challenges/repeated-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup 

 

java에서 문자열말고 문자는 "==" 으로 비교 가능하다. 

문자 자체를 비교하기 때문인데, String.matches(), Character.compare() 메소드도 사용가능하다.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {
    public static long repeatedString(String s, long n) {
        long string_len = s.length();
        long chunk = n / string_len;
        long rest = n % string_len;
        long a_cnt = s.chars()
                    .filter(c -> c == 'a')
                    .count();
        long rest_cnt = 0;
        
        for(int i=0;i<rest;i++){
            if(s.charAt(i) =='a'){
                rest_cnt += 1;
            }
        }

        return a_cnt * chunk + rest_cnt;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String s = bufferedReader.readLine();

        long n = Long.parseLong(bufferedReader.readLine().trim());

        long result = Result.repeatedString(s, n);

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

        bufferedReader.close();
        bufferedWriter.close();
    }
}