161. One Edit Distance
Explanation:
The problem asks us to determine if two given strings are one edit distance apart. An edit distance is defined as inserting a character, deleting a character, or replacing a character in one of the strings to make them equal.
To solve this problem, we can iterate through both strings simultaneously and compare the characters. If we find a difference, we need to check if it can be resolved within one edit operation. We can handle this by considering three cases:
- If the lengths of the strings differ by more than 1, they can't be one edit distance apart.
- If the lengths are equal, we can allow only one character to be different.
- If the lengths differ by 1, we can allow one string to have an additional character.
Time complexity: O(n) Space complexity: O(1)
:
class Solution {
public boolean isOneEditDistance(String s, String t) {
int m = s.length();
int n = t.length();
if (Math.abs(m - n) > 1) {
return false;
}
for (int i = 0; i < Math.min(m, n); i++) {
if (s.charAt(i) != t.charAt(i)) {
if (m == n) {
return s.substring(i + 1).equals(t.substring(i + 1));
} else if (m < n) {
return s.substring(i).equals(t.substring(i + 1));
} else {
return s.substring(i + 1).equals(t.substring(i));
}
}
}
return Math.abs(m - n) == 1;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.