Skip to main content Link Menu Expand (external link) Document Search Copy Copied

24510. 시간복잡도를 배운 도도

2022 ICPC Sinchon Winter Algorithm Camp Contest Open


문제 링크: https://www.acmicpc.net/contest/problem/760/1

문제 풀이

각 라인별로 문자열 “for”과 “while”의 등장횟수를 센 뒤에, 가장 많은 등장횟수를 가진 라인의 등장횟수를 답으로 출력하면 된다.

함수로 구현할 때,

  1. 하나의 라인에 대하여 반복문의 등장 횟수를 셀 함수 countLoops()
  2. Stdin1 에서 입력을 받고 각 라인별 등장횟수중 최댓값을 찾을 메인함수

이렇게 크게 두 가지의 함수로 나누어 구현하면 될 것 같다.

Python 3

str.count() 이용

Python의 내장함주중 str.count()를 이용하면 어이없을 정도로 너무나도 쉽게 substring의 수를 셀 수 있다.

import sys


def solve():
    answer = 0
    number_of_lines = int(sys.stdin.readline())
    for i in range(number_of_lines):
        line = sys.stdin.readline()
        answer = max(answer, count_loops(line))
    print(answer)


def count_loops(line: str) -> int:
    return line.count("for") + line.count("while")


if __name__ == "__main__":
    solve()
  1. 표준입력 (Standard Input) 


Back to top