One Edit Distance
给两个字符串s和t, 问s和t是不是之差一个edit distance. 先看两个的长度, 差超过2个肯定不行, 然后一样的话就看是不是都一样, 不一样(差一个) 就从前往后扫, 然后看substring.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Solution { public boolean isOneEditDistance(String s, String t) { if(s.equals(t)) return false; for (int i = 0; i < Math.min(s.length(), t.length()); i++) { if(s.charAt(i) != t.charAt(i)) { if(s.length() == t.length()){ if(s.substring(i+1).equals(t.substring(i+1))) return true; else return false; } else { if(s.length() > t.length()){ if(s.substring(i+1).equals(t.substring(i))) return true; else return false; } else{ if(s.substring(i).equals(t.substring(i+1))) return true; else return false; } } } } return Math.abs(s.length() - t.length()) <= 1; } } |