티스토리 뷰

참고: https://leetcode.com/problems/longest-repeating-character-replacement/

 

Longest Repeating Character Replacement - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

참고: https://docs.python.org/3/library/stdtypes.html#range

 

Built-in Types — Python 3.9.5 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org


자바나 파이썬에서 가장 많이 만나볼 수 있는 반목문 중 하나는 for문일 것이다.

자바와 파이썬의 for문의 대표적인 구조는 아래와 같다.

Java

for(int i=0;i<limit;i++) {
	...
}

Python

for i in range(limit):
	...

 

일반적인 상황에서 두 반복문의 차이를 발견하기 어렵지만, 반복문 밖에서 i를 초기화하고, 반복문이 종료된 후 i를 출력하면 차이가 발생한다. 그 예로 위 리트코드의 문제를 사용한다.

 

Java

public static int characterReplacement(String s, int k) {
        int left=0, right=0;
        int[] counts = new int[26];

        for (right=1;right<=s.length();right++) {
            char ch = s.charAt(right-1);
            counts[ch - 'A']++;
            int maxCharN = findMax(counts);

            if (right - left - maxCharN > k) {
                counts[s.charAt(left) - 'A']--;
                left++;
            }
        }
        // right가 s.length()를 초과한 후 종료
        return right - left - 1;
    }

Python

def characterReplacement(self, s: str, k: int) -> int:
        left = right = 0
        counts = collections.Counter()

        for right, char in enumerate(s, 1):
            counts[char] += 1
            most_char_n = counts.most_common(1)[0][1]
            
            if right - left - most_char_n > k:
                counts[s[left]] -= 1
                left += 1
        # right에 1이 더해지지 않고 종료
        return right - left

 

두 소스 코드의 차이점은 자바의 리턴 값은 right - left - 1인 반면, 파이썬은 right - left이라는 것이다.

 

이러한 차이점은 파이썬의 range가 불변 시퀀스 타입을 나타내는 것에서 발생한다. 파이썬의 도큐먼트를 살펴보면 아래와 같다.

다시말해, 자바는 right 변수를 1씩 증가시키며 반복문을 수행하는 반면, 파이썬은 [0, 1, 2, ..., limit-1]의 시퀀스에서 하나씩 가져오기 때문에 반복문 종료 후 right의 값에서 차이가 발생하는 것이다.

 

 

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함