From af7708edbfe25d47cc7614748948ff9fc48d922d Mon Sep 17 00:00:00 2001 From: evenix Date: Wed, 2 Aug 2017 23:08:21 -0400 Subject: [PATCH] Update Q1_05_One_Away.rb You can use the length of the intersection of the two string converted to an array to determine if there's one edit away. --- Chap_1_Arrays_and_Strings/Q1_05_One_Away.rb | 46 +++++++-------------- 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/Chap_1_Arrays_and_Strings/Q1_05_One_Away.rb b/Chap_1_Arrays_and_Strings/Q1_05_One_Away.rb index 9044372..c092709 100644 --- a/Chap_1_Arrays_and_Strings/Q1_05_One_Away.rb +++ b/Chap_1_Arrays_and_Strings/Q1_05_One_Away.rb @@ -1,34 +1,20 @@ def one_away(s1, s2) - if s1 == s2 - return true - elsif (s1.length - s2.length).abs > 1 - return false - end + s1_array = s1.split('') + s2_array = s2.split('') - string_1 = s1.length >= s2.length ? s1 : s2 - string_2 = s1.length < s2.length ? s1 : s2 + intersection_length = (s1_array & s2_array).length - chars_1 = string_1.split('') - chars_2 = string_2.split('') - - index_1 = 0 - index_2 = 0 - edit_count = 0 - - while (index_1 < string_1.length) - if chars_1[index_1] != chars_2[index_2] - edit_count += 1 - index_2 += 1 if string_1.length == string_2.length - else - index_2 += 1 - end - - index_1 += 1 - - if edit_count > 1 - return false - end - end - - true + if s1.length >= s2.length + if intersection_length == (s1.length - 1) + true + else + false + end + elsif s1.length < s2.length + if intersection_length == (s2.length - 1) + true + else + false + end + end end