[LeetCode] 161. One Edit Distance 一个编辑距离
Given two strings S and T, determine if they are both one edit distance apart.
72. Edit Distance 的类似题目,编辑距离是从一个单词变成另一个单词的变换步骤。变换步骤可以是:插入,删除和替换。所以考虑三种情况:
1. 长度之差大于1,直接返回False
2. 长度之差等于1,长的字符串可去掉一个字符,剩下的字符串相同。
3. 长度之差等于0,两个字符串对应位置的字符只能有一处不同。
Java:
public boolean isOneEditDistance(String s, String t) { if(s==null || t==null) return false; int m = s.length(); int n = t.length(); if(Math.abs(m-n)>1){ return false; } int i=0; int j=0; int count=0; while(i<m&&j<n){ if(s.charAt(i)==t.charAt(j)){ i++; j++; }else{ count++; if(count>1) return false; if(m>n){ i++; }else if(m<n){ j++; }else{ i++; j++; } } } if(i<m||j<n){ count++; } if(count==1) return true; return false; }
Python:
class Solution(object): def isOneEditDistance(self, s, t): """ :type s: str :type t: str :rtype: bool """ if abs(len(s) - len(t)) > 1: return False for i in range(min(len(s), len(t))): if s[i] != t[i]: if len(s) == len(t): return s[i+1:] == t[i+1:] elif len(s) < len(t): return s[i:] == t[i+1:] else: return s[i+1:] == t[i:] return abs(len(s) - len(t)) == 1
Python:
class Solution(object): def isOneEditDistance(self, s, t): m, n = len(s), len(t) if m > n: return self.isOneEditDistance(t, s) if n - m > 1: return False i, shift = 0, n - m while i < m and s[i] == t[i]: i += 1 if shift == 0: i += 1 while i < m and s[i] == t[i + shift]: i += 1 return i == m
C++:
class Solution { public: bool isOneEditDistance(string s, string t) { for (int i = 0; i < min(s.size(), t.size()); ++i) { if (s[i] != t[i]) { if (s.size() == t.size()) return s.substr(i + 1) == t.substr(i + 1); else if (s.size() < t.size()) return s.substr(i) == t.substr(i + 1); else return s.substr(i + 1) == t.substr(i); } } return abs((int)s.size() - (int)t.size()) == 1; } };
类似题目:
[LeetCode] 72. Edit Distance 编辑距离
All LeetCode Questions List 题目汇总