파비의 매일매일 공부기록

2023.07.03 Today's Challenge 본문

Problem Solving/LeetCode

2023.07.03 Today's Challenge

fabichoi 2023. 7. 3. 23:45

https://leetcode.com/problems/buddy-strings/

 

Buddy Strings - LeetCode

Can you solve this real interview question? Buddy Strings - Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-ind

leetcode.com

오랫만에 푸는 시도를 해봄 ㅠㅠ 실패했지만..
생각보다 조건이 많았음.

class Solution:
    def buddyStrings(self, s: str, goal: str) -> bool:
        if len(s) != len(goal):
            return False

        if s == goal:
            freq = [0 for _ in range(26)]
            for ch in s:
                freq[ord(ch) - ord('a')] += 1
                if freq[ord(ch) - ord('a')] == 2:
                    return True
            return False

        fi, si = -1, -1

        for i in range(len(s)):
            if s[i] != goal[i]:
                if fi == -1:
                    fi = i
                elif si == -1:
                    si = i
                else:
                    return False

        if si == -1:
            return False
        
        return s[fi] == goal[si] and s[si] == goal[fi]
반응형

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

2023.07.05 Today's Challenge  (0) 2023.07.05
2023.07.04 Today's Challenge  (0) 2023.07.04
2023.07.02 Today's Challenge  (0) 2023.07.02
2023.07.01 Today's Challenge  (0) 2023.07.01
2023.06.30 Today's Challenge  (0) 2023.06.30
Comments