//GitHub https://github.com/vellimole0621
vellimole0621 - Overview
キム・ヒョンギュ . vellimole0621 has 6 repositories available. Follow their code on GitHub.
github.com
문제 - 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
문제 설명
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-indexed) such that i != j and swapping the characters at s[i] and s[j].
=> 두 문자열에서, 한 문자열의 두 글자만 순서를 서로 바꿔 다른 문자열과 같게 할 수 있는 지를 True False로 출력하라.
내 풀이 :
두 문자열이 같은 길이 인지, 한 글자는 아닌지 확인 > 두 문자열 중 다른 문자 수의 개수 확인 > 1. 다른 문자 수가 2개인 경우, 그 글자들이 서로 같고 자릿수만 다를 경우 True 2. 다른 문자 수가 0개인 경우(같은 문자열), 문자열 중 같은 글자가 있는 경우 True
class Solution:
def buddyStrings(self, s, goal):
global check
check = 0
l_s = list(s)
g_s = list(goal)
num = []
if len(l_s) != len(g_s) or len(l_s) == 1:
return False
else:
for i in range(0, len(l_s)):
if l_s[i] != g_s[i]:
num.append(i)
if len(num) == 2:
if l_s[num[0]] == g_s[num[1]] and l_s[num[1]] == g_s[num[0]]:
return True
else:
return False
elif len(num) == 0:
if l_s == g_s:
for i in range(0,len(l_s)):
for j in range(i+1,len(l_s)):
if l_s[i] == l_s[j]:
check =1
break
if check == 1:
return True
else:
return False
else:
return False
else:
return False
LeetCode에서 이 문제를 더 효율적으로 푼 코드가 있었다.
class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
len_s = len(s)
len_g = len(goal)
diff = []
countdiff = 0
if len_s != len_g:
return False
# If s==goal, check dulplicates.
if s == goal:
if len(set(s)) < len_s:
return True
else:
return False
# If s!= goal
for i, j in zip(s, goal):
if i != j:
diff.append([i,j])
if len(diff) > 2:
return False
return len(diff) == 2 and diff[0][0] == diff[1][1] and diff[0][1] == diff[1][0]
=>
1. zip() 내장 함수로 s, goal str을 튜플 형식으로 만들어서 비교
2. set() 내장 함수로, 중복 제외된 set 생성
'프로그래밍 > Python' 카테고리의 다른 글
[파이썬 Python/알고리즘] LeetCode - Unique Paths (0) | 2023.07.16 |
---|---|
[파이썬 Python/알고리즘] LeetCode - Single Number II (0) | 2023.07.04 |
[파이썬 Python/알고리즘] LeetCode - Palindrome Number (0) | 2023.07.02 |
[파이썬 Python/알고리즘] LeetCode - Two Sum (0) | 2023.06.30 |
[Python] 블랙잭 게임 (0) | 2023.02.26 |