http://lintcode.com/en/problem/edit-distance-ii/
Given two strings S and T, determine if they are both one edit distance apart.
Example
http://blog.csdn.net/sunday0904/article/details/71154703
Given s =
return
"aDb"
, t = "adb"
return
true
首先判断两个字符串的长度,是否符合一个编辑距离。然后判断是要用替换还是插入。
- public boolean isOneEditDistance(String s, String t) {
- int slen = s.length();
- int tlen = t.length();
- int temp = slen - tlen;
- if(s.equals(t)) return false;
- if(temp == 0){
- boolean flag = true;
- for(int i = 0; i< slen ;i++){
- if(s.charAt(i) != t.charAt(i)){
- if(flag){
- flag = false;
- }else{
- return false;
- }
- }
- }
- return true;
- }else if(temp == 1){
- if(s.substring(0 , tlen).equals(t)){
- return true;
- }
- boolean flag = true;
- for(int i = 0;i<slen;i++){
- if(flag){
- if(s.charAt(i) != t.charAt(i)){
- flag = false;
- }
- }else{
- if(s.charAt(i) != t.charAt(i - 1)){
- return false;
- }
- }
- }
- return true;
- }else if(temp == -1){
- if(t.substring(0 , slen).equals(s)){
- return true;
- }
- boolean flag = true;
- for(int i = 0;i<tlen;i++){
- if(flag){
- if(t.charAt(i) != s.charAt(i)){
- flag = false;
- }
- }else{
- if(t.charAt(i) != s.charAt(i - 1)){
- return false;
- }
- }
- }
- return true;
- }else{
- return false;
- }
- }