본문 바로가기
TIL - 프로그래밍/Python 알고리즘

[SWEA] 4865. 글자수 - Python

by chaemj97 2022. 2. 20.
728x90

https://swexpertacademy.com/main/learn/course/lectureProblemViewer.do

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

< 📝 문제 >

두 개의 문자열 str1과 str2가 주어진다. 문자열 str1에 포함된 글자들이 str2에 몇 개씩 들어있는지 찾고, 그중 가장 많은

 

글자의 개수를 출력하는 프로그램을 만드시오.

예를 들어 str1 = “ABCA”, str2 = “ABABCA”인 경우, str1의 A가 str2에 3개 있으므로 가장 많은 글자가 되고 3을 출력한다.

파이썬의 경우 딕셔너리를 이용할 수 있다.


< ❓ 생각 >

각 요소 하나하나 비교해서 같으면 result에 1 추가

result가 max_result보다 크면 바꾸기

- 반복


< 💻 코드 >

# T : 테스트 케이스 개수
T = int(input())
for tc in range(1,T+1):
    # str1에 포함된 글자들이 str2에 몇개씩 들어있는지
    str1 = input()
    str2 = input()
    # max_result : 그 중 가장 큰 숫자
    max_result = 0
    # 하나하나 비교
    for i in str1:
        result = 0
        for j in str2:
            # 같으면 result 1추가
            if i == j:
                result += 1
        # result가 이전 max_result보다 크면 교체
        if max_result < result:
            max_result = result
    print(f'#{tc} {max_result}')

 

728x90
반응형

댓글