LeetCode 161. One Edit Distance(编辑距离)
2016-05-25 01:40
316 查看
原题网址:https://leetcode.com/problems/one-edit-distance/
Given two strings S and T, determine if they are both one edit distance apart.
方法:两个字符串长度最多相差1,或者最多只有一个字符不同。
另一种实现(不如上一种简洁):
Given two strings S and T, determine if they are both one edit distance apart.
方法:两个字符串长度最多相差1,或者最多只有一个字符不同。
public class Solution { public boolean isOneEditDistance(String s, String t) { if (s == null && t == null) return false; if (s == null) return t.length() == 1; if (t == null) return s.length() == 1; if (s.length() < t.length()) { String temp = s; s = t; t = temp; } if (s.length() == 1 && t.length() == 0) return true; if (s.length() > t.length() + 1) return false; if (s.length() == t.length()) { int dist = 0; for(int i=0; i<s.length(); i++) { if (s.charAt(i) != t.charAt(i)) { dist ++; if (dist > 1) return false; } } return dist == 1; } else { int dist = 0; for(int i=0; i<t.length(); i++) { if (t.charAt(i) == s.charAt(i+dist)) continue; dist ++; if (dist > 1) return false; if (t.charAt(i) == s.charAt(i+dist)) continue; return false; } return dist <= 1; } } }
另一种实现(不如上一种简洁):
public class Solution { public boolean isOneEditDistance(String s, String t) { char[] sa = s.toCharArray(); char[] ta = t.toCharArray(); if (Math.abs(sa.length-ta.length) > 1) return false; if (sa.length < ta.length) { char[] temp = sa; sa = ta; ta = temp; } int i=0, j=0; int dist = 0; while (i<sa.length || j <ta.length) { if (i==sa.length) { dist++; j++; } else if (j==ta.length) { dist++; i++; } else if (sa[i]==ta[j]) { i++; j++; } else { if (i<sa.length-1 && sa[i+1] == ta[j]) { i ++; } else { i ++; j ++; } dist ++; } if (dist>1) return false; } return dist == 1; } }
相关文章推荐
- 搭电路和Altium Designer
- unity获取某个方法执行时间
- LeetCode 168. Excel Sheet Column Title(EXCEL栏目)
- LeetCode 167. Two Sum II - Input array is sorted(两数和)
- LeetCode 166. Fraction to Recurring Decimal(循环小数)
- LeetCode 169. Majority Element(众数)
- 3dsMax之CoCreateInstence() failed报错
- LeetCode 186. Reverse Words in a String II(反转单词)
- LeetCode 179. Largest Number(最大数)
- LeetCode 173. Binary Search Tree Iterator(二叉搜索树迭代器)
- LeetCode 172. Factorial Trailing Zeroes(0结尾)
- LeetCode 171. Excel Sheet Column Number(Excel列号)
- LeetCode 170. Two Sum III - Data structure design(两数和)
- 完全移除TFS2013的版本控制
- Rest API 设计最佳实践(1)
- LeetCode 350. Intersection of Two Arrays II(数组交集)
- LeetCode 174. Dungeon Game(游戏)
- LeetCode 187. Repeated DNA Sequences(重复DNA序列)
- LeetCode 351. Android Unlock Patterns(安卓解锁)
- C#匹配中文字符串的4种正则表达式分享