LeetCode 面试题 01.05. 一次编辑
题目链接:
【分析】分情况讨论:m = first.length(), n = second.length()
1.Math.abs(m - n) > 1,必然不符合要求,直接返回false;
1.m == n,判断first.equals(second),完全相同返回true
否则枚举两个字符串中的字符,只有一个字符不同时返回true;
2.m != n,交换两个字符串先,使得first为较长的,second为较短的
遍历second的过程中比对first,遇到第一个不同时,first跳过,second停留来比对first的下一个,如果还能遇到不同的,就得返回false了。
class Solution { public boolean oneEditAway(String first, String second) { if(first.equals(second)) return true; int m = first.length(); int n = second.length(); int t = 0; if(Math.abs(m - n) > 1) return false; if(m == n){ for(var i = 0; i < n; i++){ if(first.charAt(i) != second.charAt(i)) t++; if(t > 1) return false; } return true; } if(m < n){ String tmp = first; first = second; second = tmp; int tm = m; m = n; n = tm; } int j = 0; for(var i = 0; i < n; i++){ if(second.charAt(i) != first.charAt(j)) { t++; i--; } if(t > 1) return false; j++; } return true; } }
上一篇:
IDEA上Java项目控制台中文乱码