diff source pure
The diff package implements the Myers diff algorithm to compute the edit distance and generate a minimal edit script ...
The diff package implements the Myers diff algorithm to compute the edit distance and generate a minimal edit script between two strings.
Edit distance, also known as Levenshtein distance, is a measure of the similarity between two strings. It is defined as the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other.
1
2
func Format
Format converts a slice of Edit operations into a human-readable string representation. It groups consecutive edits of the same type and formats them as follows:
- Unchanged characters are left as-is
- Inserted characters are wrapped in [+...]
- Deleted characters are wrapped in [-...]
This function is useful for visualizing the differences between two strings in a compact and intuitive format.
Parameters:
- edits: A slice of Edit operations, typically produced by MyersDiff
Returns:
- A formatted string representing the diff
Example output:
Note:
func MyersDiff
MyersDiff computes the difference between two strings using Myers' diff algorithm. It returns a slice of Edit operations that transform the old string into the new string. This implementation finds the shortest edit script (SES) that represents the minimal set of operations to transform one string into the other.
The function handles both ASCII and non-ASCII characters correctly.
Time complexity: O((N+M)D), where N and M are the lengths of the input strings, and D is the size of the minimum edit script.
Space complexity: O((N+M)D)
In the worst case, where the strings are completely different, D can be as large as N+M, leading to a time and space complexity of O((N+M)^2). However, for strings with many common substrings, the performance is much better, often closer to O(N+M).
Parameters:
- old: the original string.
- new: the modified string.
Returns:
- A slice of Edit operations representing the minimum difference between the two strings.
2
1
- strings stdlib