2019๋ 11์ 9์ผ
์ถ์ฒ: https://www.udemy.com/course/11-essential-coding-interview-questions/learn/quiz/379168#overview
Write a function that takes two strings and returns True if they are one away from each other.
They are one away from each other if a single operation (changing a character, deleting a character or adding a character) will change one of the strings to the other.
-
"abcde" and "abcd" are one away (deleting a character).
-
"a" and "a" are one away (changing the only character 'a' to the equivalent character 'a').
-
"abc" and "bcc" are NOT one away. (They are two operations away.)
-
one away: ๋ฌธ์์ด ์์ ์ค ํ๋๋ง ๋นผ์ ๋ง๋ค์ด์ผ ํ๋ค.
- ๋ฌธ์์ด์ ๊ธธ์ด๊ฐ 2์ด์ ์ฐจ์ด ๋๋ฉด one away ์กฐ๊ฑด์ ์ด๊ธ๋๋ฏ๋ก False๋ฅผ ๋ฆฌํดํ๋ค.
-
๋์ฌ ์ ์๋ ๊ฒฝ์ฐ์ ์๋ ๋ค์ ๋ ๊ฐ์ง์ด๋ค.
-
- ๋ฌธ์์ด์ ๊ธธ์ด๊ฐ ๊ฐ์ ๊ฒฝ์ฐ
-
- ๋ฌธ์์ด์ด ๋ค๋ฅธ ๊ฒฝ์ฐ (๊ธธ์ด๊ฐ 1 ์ฐจ์ด ๋๋ ๊ฒฝ์ฐ)
-
- ๋ฌธ์์ด์ ๊ธธ์ด๊ฐ ๊ฐ์ ๊ฒฝ์ฐ
- ๋ ๋ฌธ์์ด์์ ๊ฐ์ ์์๊ฐ ๋ ๊ฐ ์ด์์ผ ๊ฒฝ์ฐ False, ๊ทธ ์ธ์ ๊ฒฝ์ฐ True๋ฅผ ๋ฆฌํดํ๋ค.
- ๋ฌธ์์ด์ด ๋ค๋ฅธ ๊ฒฝ์ฐ (๊ธธ์ด๊ฐ 1 ์ฐจ์ด ๋๋ ๊ฒฝ์ฐ)
- ์์ ๋ฌธ์์ด ๊ธธ์ด๋งํผ ์ํํ๋ฉฐ ๋ค๋ฅธ ์์๊ฐ ๋์์ ๋ ํด๋น ์์๋ฅผ ๊ธด ๋ฌธ์์ด์์ ๋นผ์ค๋ค.
- ์ด ๋, ์์ ๋ฌธ์์ด๊ณผ ๊ธด ๋ฌธ์์ด์ด ๊ฐ๋ค๋ฉด True ๊ฐ์ง ์๋ค๋ฉด False๋ฅผ ๋ฆฌํดํ๋ค.
def is_one_away(s1, s2):
if abs(len(s1) - len(s2)) > 1: return False
if len(s1) == len(s2):
count = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
count += 1
if count > 1: return False
return True
if len(s1) > len(s2):
longer_string = s1
shorter_string = s2
else:
longer_string = s2
shorter_string = s1
for j in range(len(shorter_string)):
if longer_string[j] != shorter_string[j]:
longer_string = longer_string[:j] + longer_string[j + 1:]
if longer_string == shorter_string:
return True
else:
return False
return True