Skip to content

Latest commit

ย 

History

History
73 lines (47 loc) ยท 2.23 KB

2019-11-09-AT-one-away-string.md

File metadata and controls

73 lines (47 loc) ยท 2.23 KB

2019๋…„ 11์›” 9์ผ

Udemy - One Away String (String) {docsify-ignore-all}

์ถœ์ฒ˜: 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.

Example

  • "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. ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ
      1. ๋ฌธ์ž์—ด์ด ๋‹ค๋ฅธ ๊ฒฝ์šฐ (๊ธธ์ด๊ฐ€ 1 ์ฐจ์ด ๋‚˜๋Š” ๊ฒฝ์šฐ)
  1. ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ
  • ๋‘ ๋ฌธ์ž์—ด์—์„œ ๊ฐ™์€ ์›์†Œ๊ฐ€ ๋‘ ๊ฐœ ์ด์ƒ์ผ ๊ฒฝ์šฐ False, ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ True๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.
  1. ๋ฌธ์ž์—ด์ด ๋‹ค๋ฅธ ๊ฒฝ์šฐ (๊ธธ์ด๊ฐ€ 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