LeetCode 161. One Edit Distance
原题链接在这里:https://leetcode.com/problems/one-edit-distance/
题目:
Given two strings s and t, determine if they are both one edit distance apart.
Note:
There are 3 possiblities to satisify one edit distance apart:
- Insert a character into s to get t
- Delete a character from s to get t
- Replace a character of s to get t
Example 1:
Input: s = "ab", t = "acb" Output: true Explanation: We can insert 'c' into s to get t.
Example 2:
Input: s = "cab", t = "ad" Output: false Explanation: We cannot get t from s by only one step.
Example 3:
Input: s = "1203", t = "1213" Output: true Explanation: We can replace '0' with '1' to get t.
题解:
若是长度相差大于1, return false. 若是长度相差等于1, 遇到不同char时, 长的那个向后挪一位. 若是长度相等, 遇到不同char时同时向后挪一位.
出了loop还没有返回,就是到目前为止都相同,那么看长度差是不是等于1. 这里等于0表示完全相同也不可以.
Time Complexity: O(Math.min(len1, len2)).
Space: O(1).
AC Java:
1 public class Solution { 2 public boolean isOneEditDistance(String s, String t) { 3 if(s == null || t == null){ 4 return false; 5 } 6 int len1 = s.length(); 7 int len2 = t.length(); 8 for(int i = 0; i < Math.min(len1, len2); i++){ 9 if(s.charAt(i) != t.charAt(i)){ 10 if(len1 == len2){ 11 return s.substring(i+1).equals(t.substring(i+1)); 12 }else if(len1 > len2){ 13 return s.substring(i+1).equals(t.substring(i)); 14 }else{ 15 return s.substring(i).equals(t.substring(i+1)); 16 } 17 } 18 } 19 return Math.abs(len1-len2) == 1; 20 } 21 }