<문제>
알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.
<정답 코드>
초기에 strlen함수의 잘못된 사용으로 시간 초과가 떴었다. 잘못된 사용의 예제와 해결은 아래의 링크에 있다.
map container를 이용한 다른 사람의 풀이로 나중에 공부할 내용
http://blockdmask.tistory.com/91
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int main() { char word[1000000]; char tmp; char answer; int count = 1; int highnum = 1; int same = 0; scanf("%s", word); int len = strlen(word); // 입력의 단어가 1개인 경우 뒤에 코드를 실행할 필요없이 바로 출력 if (len == 1) { if ('a' <= word[0] && word[0] <= 'z') word[0] = word[0] - 32; printf("%c\n", word[0]); return 0; } // 소문자를 대문자로 변환 for (int i = 0; i < len; i++) { if ('a' <= word[i] && word[i] <= 'z') word[i] = word[i] - 32; } sort(word, word + len); // 대문자로 변환된 단어들을 정렬. 뒤의 코드에서 순서대로 비교하기 위함 tmp = word[0]; // 초기 문자를 임시변수에 저장 /* 시작 + 1 지점부터 하나씩 비교해나가면서 뒤의 값이 같다면 count를 더해가며 다른 문자를 만났을 때까지 count와 현재까지의 최고 동일 문자 수인 highnum을 비교 count가 더 크다면 count값을 highnum에 저장 후 count를 1로 해주고 같은 작업을 반복 만약 hignnum과 count의 값이 같을 경우 same에 1을 저장 */ for (int i = 1; i < len; i++) { if (tmp == word[i]) count++; else count = 1; if (highnum < count) { highnum = count; answer = tmp; same = 0; } else if (highnum == count) { same = 1; tmp = word[i]; } else tmp = word[i]; } if (same == 1) printf("?\n"); else printf("%c\n", answer); return 0; } | cs |
'C++ 문제풀이' 카테고리의 다른 글
1697번 백준(Baekjoon) (0) | 2018.09.24 |
---|---|
1929번 백준(Baekjoon) (0) | 2018.09.07 |
8958번 백준(Baekjoon) (0) | 2018.09.05 |
1152번 백준(Baekjoon) (0) | 2018.09.04 |
1260번 백준(Baekjoon) (0) | 2018.08.30 |