백준 2941번 : 크로아티아 알파벳
1. 문제 설명 (2941)
예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다.
크로아티아 알파벳 | 변경 |
---|---|
č | c= |
ć | c- |
dž | dz= |
đ | d- |
lj | lj |
nj | nj |
š | s= |
ž | z= |
예를 들어, ljes=njak은 크로아티아 알파벳 6개(lj, e, š, nj, a, k)로 이루어져 있다. 단어가 주어졌을 때, 몇 개의 크로아티아 알파벳으로 이루어져 있는지 출력한다.
dž는 무조건 하나의 알파벳으로 쓰이고, d와 ž가 분리된 것으로 보지 않는다. lj와 nj도 마찬가지이다. 위 목록에 없는 알파벳은 한 글자씩 센다.
2. 분류
그냥 구현문제
3. 풀이
왜 틀렸는지 모르겠지만 switch case 를 무지성으로 사용하다가 틀린 것 같다. 보나마나 substring 하다가 범위 이상하게 잘려서 틀렸겠지.
string.endsWith() 와 string.substring() 을 활용하여 풀었다. 각각의 활용은 다음과 같다.
string.endsWith(String suffix)
- suffix에 해당하는 문자열이 string의 마지막에 왔을 시 true 를 반환한다.
비슷한 활용도로 string.startsWith(String suffix) 라는 메소드도 있다.
string.substring(int beginIndex, int endIndex)
- beginIndex 와 endIndex 사이의 문자열을 반환한다.
예를 들어 str1 = “abc”, str2 = str1.substring(0, 2) 일 시, str2 = “ab” 이다. - endIndex 를 쓰지 않을 시 beginIndex 부터 끝까지를 반환한다.
위 두가지 메소드를 적절히 활용하면 된다.
한가지 주의사항으로, 아래와 같이 endsWith() 를 활용하는 경우 “dz=” 를 “z=” 보다 먼저 판별해주어야 한다 (Line 10, 14). 순서가 바뀌어 “z=” 가 먼저 나올 시 “dz=” 는 있으나마나 한 코드가 된다.
4. 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.io.*; public class Q2941 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String cr = br.readLine(); int count = 0; while(true) { if(cr.endsWith("dz=")) { cr = cr.substring(0, cr.length() - 3); count++; } else if(cr.endsWith("c=") || cr.endsWith("c-") || cr.endsWith("d-") || cr.endsWith("lj") || cr.endsWith("nj") || cr.endsWith("s=") || cr.endsWith("z=")) { cr = cr.substring(0, cr.length() - 2); count++; } else { cr = cr.substring(0, cr.length() - 1); count++; } if(cr.equals("")) break; } bw.write(count+""); bw.flush(); bw.close(); } } | cs |
5. 결과
128ms로 잘 작동한다. 시간 초과는 다른 실험 하다가 틀림
댓글남기기