这是我的python实现。我为每个字符串使用两个数组
import unittest
# Assume characters stored in 8 bits. 256 possible characters
MAX_CHARS = 256
def is_edit(string1, string2):
"""Given two strings, return if they are one or zero edits away.
Insert, remove or replace a character."""
# If the absolute difference in length is more than one
# return false
string1_len = len(string1)
string2_len = len(string2)
if string1_len != string2_len and abs(string1_len - string2_len) > 1:
return False
# Initialize two arrays, each for each string
count1 = [0] * MAX_CHARS
count2 = [0] * MAX_CHARS
# For each character in input strings get unicode representation
# and increment counter in corresponding array
for i in string1:
count1[ord(i)] += 1
for i in string2:
count2[ord(i)] += 1
edit = 0
# compare the arrays
# If number of edits required is more than 2 return false
# This will handle replacement when given words of the same length
for i in range(MAX_CHARS):
if count1[i] != count2[i]:
edit += 1
if edit > 2:
return False
# Return false if string1 is the same as string2 (No edit required) e.g pale, pale
if not edit:
return False
return True
class EditCheckTestCase(unittest.TestCase):
"""Tests for is_edit method."""
def test_insert_missing_character(self):
"""Test insertion of character is valid."""
self.assertEqual(is_edit('pale', 'ple'), True)
def test_insert_more_than_one_character(self):
"""Test insertion of more than one character is invalid"""
self.assertEqual(is_edit('pale', 'pe'), False)
def test_append_one_character(self):
"""Test the append of one character is valid."""
self.assertEqual(is_edit('pales', 'pale'), True)
def test_append_more_than_one_character(self):
"""Test append more than one character is invalid."""
self.assertEqual(is_edit('paless', 'pale'), False)
def test_replace_one_character(self):
"""Test replacement of one character is valid"""
self.assertEqual(is_edit('pale', 'bale'), True)
def test_no_edit_character(self):
"""Test no edit required is valid."""
self.assertEqual(is_edit('pale', 'bake'), False)
self.assertEqual(is_edit('pale', 'pale'), False)
if __name__ == "__main__":
unittest.main()