백준/1 - 5000
[백준] 1701번 : Cubeditor(JAVA)
lms0806
2021. 8. 26. 18:01
728x90
https://www.acmicpc.net/problem/1701
1701번: Cubeditor
Cubelover는 프로그래밍 언어 Whitespace의 코딩을 도와주는 언어인 Cubelang을 만들었다. Cubelang을 이용해 코딩을 하다보니, 점점 이 언어에 맞는 새로운 에디터가 필요하게 되었다. 오랜 시간 고생한
www.acmicpc.net
풀이
기존 kmp알고리즘을 이용하여 이중 for문으로 substring으로 할 시 HashSet<>을 써도 메모리초과가 납니다.
kmp알고리즘에서 사용되는 함수 중 getpi만을 이용하여 하시면 됩니다.
소스코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int max = 0;
for(int i = 0; i < s.length(); i++) {
max = Math.max(max, getpi(s.substring(i, s.length())));
}
System.out.print(max);
}
public static int getpi(String s) {
int[] pi = new int[s.length()];
int j = 0, max = 0;
for(int i = 1; i < s.length(); i++) {
while(j > 0 && s.charAt(i) != s.charAt(j)) {
j = pi[j - 1];
}
if(s.charAt(i) == s.charAt(j)) {
max = Math.max(max, pi[i] = j += 1);
}
}
return max;
}
}
728x90