pjh4554   3년 전

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String word = sc.next();

word = word.toUpperCase();

int a = word.length();

int d=-1;

int[] c = new int[a];

for (int i = 0; i < a; i++) {

int b = 1;

for (int j = i + 1; j < a; j++) {

if (word.charAt(i) == word.charAt(j)) {

b++;

c[i] = b;

}

}

}

int max = -1;

for (int i = 0; i < a; i++) {

if (c[i] > max) {

max = c[i];

}

}

int count = 0;

for (int i = 0; i < a; i++) {

if (c[i] == max) {

d = i;

count++;

}

}

if (count > 1) {

System.out.println("?");

} else {

System.out.println(word.charAt(d));

}

}

}

요렇게 했는데 시간초과가 나왔습니다. 혹시 코드를 수정해야 할곳좀 알려주실수 있나요?

pjh4554   3년 전

그 bufferreader 로 했는데도 안되네요. 혹시 코드를 바꿔야 하나요?

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class five {

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String word = br.readLine();

word = word.toUpperCase();

int a = word.length();

int d=-1;

int[] c = new int[a];

for (int i = 0; i < a; i++) {

int b = 1;

for (int j = i + 1; j < a; j++) {

if (word.charAt(i) == word.charAt(j)) {

b++;

c[i] = b;

}

}

}

int max = -1;

for (int i = 0; i < a; i++) {

if (c[i] > max) {

max = c[i];

}

}

int count = 0;

for (int i = 0; i < a; i++) {

if (c[i] == max) {

d = i;

count++;

}

}

if (count > 1) {

System.out.println("?");

} else {

System.out.println(word.charAt(d));

}

}

}

polk4596   3년 전

1. 

우선

System.out.println("?"); 대신에

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

bw.write("?");를 사용하시는걸 추천합니다.

2.

보통 시간초과되면 이중 for문이 문제인 경우가 많습니다.

for (int i = 0; i < a; i++) {

int b = 1;

for (int j = i + 1; j < a; j++) {

if (word.charAt(i) == word.charAt(j)) {

b++;

c[i] = b;

}

}

}

I번째 글자가 J번째 글자와 같은지 비교 후 카운트를 늘리는 방법은, 문자열의 길이가 90이 되면

89!번 (16507955160908461081216919262453619309839666236496541854913520707833171034378509739399912570787600662729080382999756800000000000000000000번)

을 계산해야합니다.

(채점 진행시에 길이가 900000인 문자열이 나온다면, 899999!번을 확인해야합니다.)


여러가지 푸는 방법이 있겠지만, 

1. Set를 활용한다면

set에 문자가 있는지 확인후, 없으면 집어넣고 있으면 count를 늘리는 방법과

2. Map을 활용한다면

Map에 문자가 있는지 확인후, 없으면 집어넣고 있으면 value를 1씩 늘리는 방법

이 있고, 90의 길이를 가진 문자열이여도

90번만 체크하면 됩니다.

댓글을 작성하려면 로그인해야 합니다.