파비의 매일매일 공부기록

2023.07.09 Today's Challenge 본문

Problem Solving/LeetCode

2023.07.09 Today's Challenge

fabichoi 2023. 7. 9. 23:45

https://leetcode.com/problems/substring-with-largest-variance/

 

Substring With Largest Variance - LeetCode

Can you solve this real interview question? Substring With Largest Variance - The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not

leetcode.com

난이도가 조금 있던 문제임.
서브 스트링은 생각보다 여러 베리에이션 있는 것 같다.

class Solution:
    def largestVariance(self, s: str) -> int:
        cnt1, cnt2, max_variance = 0, 0, 0
        pairs = [(l1, l2) for l1 in set(s) for l2 in set(s) if l1 != l2]
        for runs in range(2):
            for pair in pairs:
                cnt1 = cnt2 = 0
                for letter in s:
                    if letter not in pair:
                        continue
                    if letter == pair[0]:
                        cnt1 += 1
                    elif letter == pair[1]:
                        cnt2 += 1
                    if cnt1 < cnt2:
                        cnt1 = cnt2 = 0
                    elif cnt1 > 0 and cnt2 > 0:
                        max_variance = max(max_variance, cnt1 - cnt2)
            s = s[::-1]
        return max_variance
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.07.11 Today's Challenge  (0) 2023.07.11
2023.07.10 Today's Challenge  (0) 2023.07.10
2023.07.08 Today's Challenge  (0) 2023.07.08
2023.07.07 Today's Challenge  (0) 2023.07.07
2023.07.06 Today's Challenge  (0) 2023.07.06
Comments